1. 程式人生 > >21、自動裝配[email protected]&@Inject

21、自動裝配[email protected]&@Inject

21、自動裝配[email protected]&@Inject

  • Spring 還支援使用@Resource(JSR250)和@Inject(JSR330)[Java規範的註解]
  • AutowiredAnnotationBeanPostProcessor 完成解析自動裝配功能

21.1 @Resource

  • 可以和@Autowired一樣實現自動注入功能,預設是按照元件名稱進行裝配的。
  • 沒有能支援@Primary功能,沒有支援@Autowired(required = false)

21.2 @Inject

  • @Inject 需要匯入javax.inject
    依賴才能使用,和@Autowired功能一樣,但沒有required=false屬性值設定。

22.3 區別

  • @Autowired 是Spring定義的,@Resource@Inject 都是Java的規範
<!-- https://mvnrepository.com/artifact/javax.inject/javax.inject -->
<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>

22.4 程式碼例項

//    @Autowired(required = false)
//    @Qualifier("bookRepository")
//    @Resource(name = "bookRepository")
    @Inject
    private BookRepository bookRepository2;