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。

posted on   乐之者v  阅读(10456)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示