首页 > 其他分享 >声明Spring Bean和注入Bean的几种常用注解和区别

声明Spring Bean和注入Bean的几种常用注解和区别

时间:2022-11-04 14:35:50浏览次数:49  
标签:依赖 Autowired Spring Bean 注解 注入


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 

Matches by Type
Restricts by Qualifiers
Matches by Name

Matches by Name
Matches by Type
Restricts by Qualifiers (ignored if match is found by name)

 

标签:依赖,Autowired,Spring,Bean,注解,注入
From: https://blog.51cto.com/u_15861563/5823760

相关文章