免费已备案二级域名网站,唐山网页设计,怎么建设网站阿里云,海南网络公司网站建设spring依赖注入在从Spring跳到类型安全依赖注入之前#xff0c;我想讨论一下我们之前所做的方式。 我们一直在借助Spring的Autowired注释按类型使用依赖项注入。 像这样的东西会注入Spring Bean。 Autowired
private StudentDao studentDao; // Autowires by type. Injects th… spring依赖注入 在从Spring跳到类型安全依赖注入之前我想讨论一下我们之前所做的方式。 我们一直在借助Spring的Autowired注释按类型使用依赖项注入。 像这样的东西会注入Spring Bean。 Autowired
private StudentDao studentDao; // Autowires by type. Injects the instance whose type is StudentDao 但是如果我们有一种类型的多个Spring bean那么我们将使用Qualifier Annotation和Autowired实际上是按名称注入spring bean。 具有以下内容的应用程序上下文 bean idstudentDao1 classStudentDao /
bean idstudentDao2 classStudentDao / 因此现在如果我们有两个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.htmlspring依赖注入