欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

Spring3:类型安全依赖项注入

发布时间:2023/12/3 javascript 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Spring3:类型安全依赖项注入 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
在从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 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

总结

以上是生活随笔为你收集整理的Spring3:类型安全依赖项注入的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。