Spring 中Bean及@Bean的理解

注解

凡是拥有子类及带有方法或属性的类都要加上注解注册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。

猜你喜欢

转载自z724130632.iteye.com/blog/2374311