Spring 中Bean及@Bean的理解
程序员文章站
2022-05-23 10:26:35
...
注解
凡是拥有子类及带有方法或属性的类都要加上注解注册Bean到Spring IoC中。
我们在微博上@某某,对方会优先看到这条信息,并给你反馈,那么在Spring中,你标识一个@符号,那么Spring就会来看看,并且从这里拿到一个Bean或者给出一个Bean
使用Bean的注解
即是把已经在xml文件中配置好的Bean拿来用,完成属性、方法的组装;比如@Autowired , @Resource,可以通过byTYPE(@Autowired)、byNAME(@Resource)的方式获取Bean;
注册Bean的注解
@Component , @Repository , @Controller , @Service , @Configration这些注解都是把你要实例化的对象转化成一个Bean,放在IoC容器中,等你要用的时候,它会和上面的@Autowired , @Resource配合到一起,把对象、属性、方法完美组装。
@Bean原理
Indicates that a method produces a bean to be managed by the Spring container.
<h3>Overview</h3>
<p>The names and semantics of the attributes to this annotation are intentionally
similar to those of the {@code <bean/>} element in the Spring XML schema. For
example:
<pre class="code">
@Bean
public MyBean myBean() {
// instantiate and configure MyBean obj
return obj;
}
</pre>
意思是,@Bean明确指示了产生一个被Spring容器管理的bean的方法。
Spring在启动的时候,检测到@Bean的时,默认会在容器中注入一个以方法名命名的Bean。
推荐阅读
-
Spring的并发问题——有状态Bean和无状态Bean
-
品Spring:SpringBoot轻松取胜bean定义注册的“第一阶段”
-
详解Spring Bean的循环依赖解决方案
-
Spring中Bean的生命周期使用解析
-
spring如何使用命名空间p简化bean的配置
-
spring5 源码深度解析----- 被面试官给虐懵了,竟然是因为我不懂@Configuration配置类及@Bean的原理
-
Spring学习之Bean的装配多种方法
-
理解文章中锚文本的概述、形式及作用
-
通过实例解析spring bean之间的关系
-
spring源码分析系列5:ApplicationContext的初始化与Bean生命周期