Spring Cloud Alibaba-Annotation(九)

常見註解比較

  • @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
        複製代碼
相關文章
相關標籤/搜索