像這樣的東西會注入Spring Bean。
@Autowired
private StudentDao studentDao; // Autowires by type. Injects the instance whose type is StudentDao
但是,如果我們有一種類型的多個Spring bean,那么我們將使用Qualifier Annotation和Autowired,實際上是按名稱注入spring bean。
具有以下內容的應用程序上下文:
<bean id="studentDao1" class="StudentDao" />
<bean id="studentDao2" class="StudentDao" />
因此,如果現在有兩個StudentDao實例(studentDao1和studentDao2),則可以按名稱注入spring bean。
@Autowired
@Qualifier("studentDao1")
private StudentDao studentDao1;@Autowired
@Qualifier("studentDao2")
private StudentDao studentDao2;
使用JSR-250指定的資源注釋可以實現相同的目的。 因此,我們可以使用此注釋將bean注入到字段或單參數方法中。 自動裝配比Resource靈活得多,因為它可以與多參數方法以及構造函數一起使用。
我們可以通過以下方式使用Resource注解按名稱注入bean。
@Resource
private StudentDao studentDao1;
Spring 3中的類型安全依賴項注入
使用@Qualifier定義自定義注釋
要在不指定名稱的情況下識別注入的bean,我們需要創建一個自定義注釋。 這等效于在CDI中使用JSR 330批注(Inject)的過程。
@Target({ElementType.Field, ElementType.Parameter})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @Interface Student {
}
現在將此自定義注釋分配給EntityDao接口的實現
@Component
@Student
public class StudentDao implements EntityDao {
}
@Component告訴Spring這是一個bean定義。 每當使用EntityDao的引用時,Spring IoC就會使用@Student批注將StudentDao標識為EntityDao的實現。
使用@Autowired和自定義限定符注入bean
這樣的東西。
@Autowired
@Student
private EntityDao studentDao; // So the spring injects the instance of StudentDao here.
這減少了字符串名稱的使用,因為字符串名稱可能會拼寫錯誤并且難以維護。
參考: 如何在Spring 3中使用類型安全依賴項注入? 來自我們的JCG合作伙伴 Saurab Parakh在Coding is Cool博客上。
翻譯自: https://www.javacodegeeks.com/2012/05/spring-3-type-safe-dependency-injection.html