常见注解比较
- @Resource & @Autowired
- 相同点
- 都可以实现注入bean
- 写在字段/setter处
- 不同点
- @Autowired是spring的注解,而@Resource不是,但是spring支持
- @Autowired是byType(根据类型)注入,默认情况下要求依赖必须存在,配置required=false表示依赖可为null,如果要实现byName(根据名称)需要集合@Qualifier
// 1 @Autowired @Qualifier("userService")- @Resource
- name & type:名称+类型,找不到/不唯一抛出异常
- name:根据名称,找不到/不唯一抛出异常
- type:根据类型,找不到/不唯一抛出异常
- 不指定:byName,找不到则回退为原始类型
// 等价1 @Resource("userService")
- 相同点
- @Repository & @Component & @Service & @Controller
- 相同点
- 作用相同:注入组件
- 不同点
- 意义不同
- @Component:通用bean
- @Controller:表现层bean
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component- @Service:业务层bean
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component- @Repository:数据访问层bean
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component
- 意义不同
- 相同点