【问题标题】:Is there an equivalent of CDI's @Default qualifier in Spring?Spring 中是否有相当于 CDI 的 @Default 限定符?
【发布时间】:2013-11-07 16:46:30
【问题描述】:

在 CDI 中,我可以这样做:

// Qualifier annotation
@Qualifier
@inteface Specific{}

interface A {}

class DefaultImpl implements A {}

@Specific
class SpecificImpl implements A {}

然后在课堂上:

@Inject
A default;

@Inject
@Specific
A specific;

之所以有效,是因为 @Default 限定符自动分配给未指定任何限定符的注入点。

但我正在使用 Spring 并且无法执行该操作。

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException

问题是“默认”注入(没有限定符)已经在很多我无法更改的代码中使用,我需要为我的用户提供另一个可能的A 实现。

我知道我可以通过 bean 名称注入我的新实现,但我想避免它。

Spring 中有什么可以帮助我实现它的吗?

【问题讨论】:

    标签: java spring dependency-injection


    【解决方案1】:

    有人指着我说@Primary 正是这样做的。我试过了,效果很好:

    @Primary
    class DefaultImpl implements A {}
    

    就我而言,DefaultImpl 在 xml 中:

    <bean id="defaultImpl" class="DefaultImpl" primary="true"/>
    

    【讨论】:

      【解决方案2】:

      我本可以将此添加为评论,但我想添加一些带有格式的代码来解释我的观点,这就是我添加明确答案的原因。

      除了您所说的之外,您实际上还可以在 Spring 中利用您的特定元注释,如下所示:

      以这种方式使用 Spring 特定的 org.springframework.beans.factory.annotation.Qualifier 注释重新定义 @Specific

      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.context.annotation.Primary;
      
      import java.lang.annotation.ElementType;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      
      @Qualifier
      @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
      @Retention(RetentionPolicy.RUNTIME)
      @Primary
      public @interface Specific {
      }
      

      我现在也用@Primary 注释标记了特定注释。

      有了这个,你的旧代码应该可以工作了:

      @Specific
      class DefaultImpl implements A {}
      

      【讨论】:

      • 但就我而言,DefaultImpl 不是@Specific。它的 SpecificImpl 必须是 @Specific。 DefaultImpl 必须是Primary
      猜你喜欢
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 2020-12-22
      相关资源
      最近更新 更多