我不确定如何在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中找到的内容并没有在我的案例中编译。如何使用我的自定义限定符?
答案 0 :(得分:3)
您需要将属性值添加到BigBean注释中
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface BigBean {
String value() default "";
}
答案 1 :(得分:0)
这现在有点旧了,不确定我的答案是否有帮助,但让我尝试。下面是注入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());
}
}