【问题标题】:Custom @Qualifier with Spring autoconfig使用 Spring 自动配置自定义 @Qualifier
【发布时间】:2015-09-08 11:21:47
【问题描述】:

我不确定如何在 Spring 中使用自定义限定符接口进行组件扫描和自动装配。我有一个界面:

@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface BigBean {
}

我要注入的 bean:

@Component
public class Bean {

   @Autowired
   @BigBean("A")
   private SomeBean sb;

   public SomeBean getSb() {
       return sb;
   }
   public void setSb(SomeBean sb) {
       this.sb = sb;
   }
}

和要通过自定义限定符区分的同一类型的bean:

@Component
@BigBean("A") //<-????
public class SmallBeanA implements SomeBean{
}

@Component
public class SmallBeanB implements SomeBean{
}

我在spring documentation 中找到的内容在我的情况下无法编译。如何使用我拥有的这个自定义限定符?

【问题讨论】:

  • 请通过添加您得到的编译错误来编辑您的问题。

标签: java spring spring-mvc


【解决方案1】:

您需要将属性值添加到 BigBean 注释中

@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface BigBean {

    String value() default "";
}

【讨论】:

  • 好的,修复了 Bean 中的编译器错误,现在如何使用这个限定符来实际指向一个实例?我应该如何标记 SmallBeanA?
  • 您是否使用了正确的@Qualifier 注释,如果您的代码应该可以工作的话。
  • 我用过:import org.springframework.beans.factory.annotation.Qualifier;我不相信它应该工作,我什至没有在 SmallBeanA 中编译错误
  • 在Bean类中修改@Autowired @Qualifier("A") private Bean bean;
  • 让我澄清一下:我想注入 SomeBean 的选定实例(两个可用实例之一)而不是 Bean
【解决方案2】:

现在这个有点老了,不确定我的回答是否有帮助,但让我试试。下面是注入 SomeBean 的选定实例的代码。


@Qualifier
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface BigBean {
    String value() default "";
}


public interface SomeBean { 
}


@Component
@BigBean("A")
public class SmallBeanA implements SomeBean {
    private SmallBeanA() {
        System.out.println("SmallBeanA constructed");
    }
    @Override
    public String toString() {
        return "SmallBeanA";
    }
}


@Component
@BigBean("B")
public class SmallBeanB implements SomeBean{
    private SmallBeanB() {
        System.out.println("SmallBeanB constructed");
    }
    @Override
    public String toString() {
        return "SmallBeanB";
    }
}


@Component
public class Bean {
    @Autowired
    @BigBean("A")
    private SomeBean sb;
    public SomeBean getSb() {
        return sb;
    }
    @Override
    public String toString() {
        return "Bean [sb=" + sb + "]";
    }
}



public class QualifierTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
        Bean myBean = context.getBean(Bean.class);
        System.out.println(myBean.getSb().toString());
        //OR
        System.out.println(myBean.toString());
    }
}

【讨论】:

    猜你喜欢
    • 2020-11-06
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    相关资源
    最近更新 更多