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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值