【归纳】springboot中的IOC注解:注册bean和使用bean
目前了解的springboot中IOC注解主要分为两类:
1. 注册bean:@Component和@Repository、@Service、@Controller 、@Configuration
共同之处:这些注解都使用在类上,将类标识为Bean,由Spring扫描到后会生成一个单例bean放到容器中。
不同之处在于:
- @Component是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层;
- @Repository、@Service、@Controller 都包含@Component注解:
@Repository | 一般修饰持久层——Dao层 |
@Service | 一般修饰服务层(或业务层)——Service层 |
@Controller | 通常作用在控制层——Controller层 |
- @Configuration,在@Component的基础上,会对修饰的类做一个增强(利用CGLIB动态代理)。它一般用来修饰配置类——Configuration文件夹。
注:在类上使用以上注解后,还可以用@Bean注解修饰方法,它很明确地告诉被注释的方法产生一个Bean,然后交给Spring容器
2. 使用bean:@Autowired、@Resource
- @Autowired与@Resource都可以用来装配bean, 都可以写在字段上,或写在setter方法上
- @Autowired默认以Type方式注入
- @Resource默认以Name方式注入,但它可以指定为Type方式(传Type值即可),也可以指定为Name和Type同时皆有的方式(那么必须找到一个Bean,它的Name和Type同时满足才可以注入)
示例:
注册bean
@Configuration
public class MyBeans { @Bean("autowire") public Integer autowire_bean(){ return 1; } @Bean("resource_name1") public String resource_bean1(){ return "this is resource_bean1"; } @Bean("resource_name2") public String resource_bean2(){ return "this is resource_bean2"; } }
使用bean:
@RestController //@RestController与@Controller有关 public class MyController { //@Autowired默认按类型注入,如果同一类型有多个bean就报错 @Autowired private Integer autowire_bean; //@Resource支持name注入或type注入,或同时指定两者注入(需同时满足name和type) @Resource(name = "resource_name1") private String resource_bean1; @Resource(name = "resource_name2",type = String.class) private String resource_bean2; @GetMapping("/autowire_bean") public String getAutowire_bean(){ return "autowire_bean: " + autowire_bean + "<br>resource_bean1: " + resource_bean1 + "<br>resource_bean2: " + resource_bean2; } }
结果:
from Chu
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了