您现在的位置是:首页 > 个人日记个人日记
spring-06-使用注解注入
2019-02-03 18:42:21【个人日记】484人已围观
简介使用注解方式进行Bean管理,非常方便
使用注解注入
三种标签
首先配置spring-config.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--扫描这些类的注解--><context:component-scan base-package="com.huangxin.spring"></context:component-scan></beans>
当简单数据类型则使用@Component,因为没有使用setter方法,使用反射,所以可以删除setter方法,@Component(这里面可以起名称,等同于xml配置中的id属性),当赋值时使用@Value(填写值)
package com.huangxin.spring;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Component("id")//取代之前Bean标签里的class属性//如果不使用括号里自定义的,则默认名称为方法名public class Message {//通过反射@Value("hello java")private String message;private String name;public Message(String message, String name) {this.message = message;this.name = name;}Message() {System.out.println("初始化完成");}public String getName() {return name;}public void setName(String name) {this.name = name;}public void init() {System.out.println("init...");}public void destroy() {System.out.println("destroy");}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}
当使用service层
package com.huangxin.spring.service.Impl;import com.huangxin.spring.service.MessageService;import org.springframework.stereotype.Service;@Service("impl02")public class MessageServiceImpl02 implements MessageService {public void deleteById(Long id) {System.out.println("Impl02=已删除id=" + id + "的信息");}}
这里实例化直接使用@Service(方法等同于@Component()使用方法)
当使用复杂对象注入时使用@Controller(名称)
赋值使用@Autowired但仅限于有一个实现类,如有多个则使用 @Qualifier(填写需要使用的id),当有多个实现类时也可以使用@Resource(name="这里使用id")
package com.huangxin.spring.controller;import com.huangxin.spring.service.MessageService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;@Controller("controller")public class MessageController {// @Autowired()//接口唯一实现类时可以直接使用//如果要使用则实例化实现类@Autowired@Qualifier("impl01")//若要使用不唯一的实现类,则需要加入Qualifier注解,需填写Bean的名称,也可以使用Resource()直接使用名称private MessageService messageService;public void doGet(Long id) {messageService.deleteById(id);}}
注意
1) 以上三个注解用法相同,都是为类创建Bean
2) 当使用不同注入时应使用不同的注解
两种生命周期
* @PostConstruct//初始化方法,对象创建时调用
- @PreDestroy//当对象被摧毁时调用的方法
作用域
- @scope(单例/多例)
Tags: JavaWeb
上一篇: spring-02-配置细节
下一篇: mybatis-06-映射关系
相关文章
随机图文
评论区
2025-11-09 06:13:36
站长
没有登录功能是为了方便大家留言,但留言接口现在被恶意攻击,将关闭留言接口,如有疑问,请联系我的QQ 1538933906/同微信
