0%

spring-annotation

记录 spring 中常见注解

声明 Bean

声明Bean的注解有:

  • @Component 没有明确角色的组件
  • @Service 在业务逻辑层(Service层)使用
  • @Repositpry 在数据访问层(dao层)使用
  • @Controller 用于标注控制层组件
  • @RestController

@Component

1
2
3
4
5
6
7
8
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default "";

}
  1. @Component作用在类上
  2. @Component注解作用域默认为singleton
  3. 使用注解配置和类路径扫描时,被@Component注解标注的类会被Spring扫描并注册为Bean
  4. @Component使用在不确定哪一个层的时候使用,可以作用在任何层次,把普通pojo实例化到spring容器
  5. 不推荐使用@Component注解,而应该使用它的扩展,如@Service、@Repository

@Service

1
2
3
4
5
6
7
8
9
10
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

@AliasFor(annotation = Component.class)
String value() default "";

}
  1. @Service是@Component注解的一个特例,作用在类上
  2. @Service注解作用域默认为singleton
  3. 使用注解配置和类路径扫描时,被@Service注解标注的类会被Spring扫描并注册为Bean
  4. @Service用于标注业务层组件,表示定义一个bean
  5. @Service使用时没有传参数,Bean名称默认为当前类的类名,首字母小写
  6. @Service(“serviceBeanId”)或@Service(value=”serviceBeanId”)使用时传参数,使用value作为Bean名字

自动装配

有关自动装配的注解

  1. @Resource
  2. @Autowired

@Resource

@Resource,它在语义上被定义为通过其唯一的名称来标识特定的目标组件,其中声明的类型与匹配过程无关。如果没有明确指定名称,则默认名称是从字段名称或设置方法(get、set方法)派生的。 如果用在字段上,则采用字段名称; 如果用在在setter方法,它采用其属性名称(例如getProperty()方法,取property做为属性名称)。

@Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.If no name is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name.

  • @Resource默认按byName自动注入。
  • 既不指定name属性,也不指定type属性,则自动按byName方式进行查找。如果没有找到符合的bean,则回退为一个原始类型进行进行查找,如果找到就注入。
  • 只是指定了@Resource注解的name,则按name后的名字去bean元素里查找有与之相等的name属性的bean。
  • 只指定@Resource注解的type属性,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常。

@Autowired

@Autowired默认先按byType进行匹配,如果发现找到多个bean,则又按照byName方式进行匹配,如果还有多个,则报出异常。

@Qualifier

@Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配,其中@Qualifier不能单独使用。