Spring 声明Bean的注解:
- @Component: 组件,没有明确的角色。
- @Service : 在业务逻辑层(Service层)使用。
- @Repository: 再数据访问层(Dao层)使用。
- @Controller: 再展现层(MVC->Spring MVC)使用。
Spring 注入Bean的注解:
- @Autowired:Spring提供的注解。
- @inject:JSR-330提供的注解。
- @Resource:JSP-250提供的注解。
‘@Autowired’ 和‘@Inject’他们都是通过‘AutowiredAnnotationBeanPostProcessor’ 类实现的依赖注入,二者具有可互换性。
‘@Resource’通过 ‘CommonAnnotationBeanPostProcessor’ 类实现依赖注入,即便如此他们在依赖注入时的表现还是极为相近的。
以下是他们在实现依赖注入时执行顺序的概括:
@Autowired and @Inject
@Autowired and @Inject
- Matches by Type
- Restricts by Qualifiers
- Matches by Name
@Resource
- Matches by Name
- Matches by Type
- Restricts by Qualifiers (ignored if match is found by name)
参考: