Spring中几组容易混淆的注解

文章目录
  1. 1. @Resource VS @Autowired
  2. 2. @Component VS @Bean

@Resource VS @Autowired

  1. @Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上。
  2. @Autowired默认按类型装配(这个注解是属于Spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用。
  3. @Resource(这个注解属于J2EE的),默认安装名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行安装名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

推荐使用:@Resource注解在字段上,这样就不用写setter方法了,并且这个注解是属于J2EE的,减少了与spring的耦合。这样代码看起就比较优雅。

@Component VS @Bean

@Component Preferable for component scanning and automatic wiring.

When should you use @Bean ?

Sometimes automatic configuration is not an option. When? Let’s imagine that you want to wire components from 3rd-party libraries (you don’t have the source code so you can’t annotate its classes with @Component), so automatic configuration is not possible.

The @Bean annotation returns an object that spring should register as bean in application context. The body of the method bears the logic responsible for creating the instance.

example:

1
2
3
4
5
6
7
8
@Bean  
@Scope("prototype")
public SomeService someService() {
switch (state) {
case 1:return new Impl1();
case 2:return new Impl2();
default: return new Impl();
}}

However there is no way to do that with @Component.