像这样的东西会注入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