Spring依赖注入:注解注入


注解注入顾名思义就是通过注解来实现注入,

Spring和注入相关的常见注解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。


1.@Autowired是自动注入,自动从spring的上下文找到合适的bean来注入

@Autowired(required=true)表示必须找到匹配的Bean,否则将报异常。

@Autowired默认按类型匹配注入Bean

在Spring中,@Autowired注入的类型可以是接口

比如,在Service层中注入Dao,如下示:

@Autowired
private UserDao userDao;

 


2.@Resource要求提供一个Bean名称的属性,如果属性为空,自动采用标注处的变量名和方法名作为Bean的名称 。

@Resource默认按名称匹配注入Bean

比如,在Controller层中注入Service,名称为Service的实现类,如下示

@Resource(name = "userServiceImpl")
 private UserService userService;

另外要注意,@Resource是java自带的注解,不是Spring中的注解。@Resource注解完整的包路径为import    javax.annotation.Resource;

 

3.@Qualifier 指定注入bean的名称

比如,在Controller层中注入Service,名称为Service的实现类,如下示

 @Autowired
 @Qualifier("userServiceImp")
 private UserSerevice userService;


4.@Service,@Controller,@Repository分别标记类是Service层,Controller层,Dao层的类,spring扫描注解配置时,会标记这些类要生成bean。

@Repository用于标注数据访问组件,即DAO组件

@Service,@Controller 这些注解要放在接口的实现类上,而不是接口上面。
5.@Component是一种泛指,标记类是组件,spring扫描注解配置时,会标记这些类要生成bean。

6.@Scope用于指定Bean的作用范围

7.@Autowired和@Resource是用来修饰字段,构造函数,或者设置方法,并做注入的。

而@Service,@Controller,@Repository,@Component则是用来修饰类,标记这些类要生成bean。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM