ApplicationContext経由でBeanを取得するときにアノテーションを使用するのは、@Qualifier
アノテーションの目的ではありません。しかし、何らかの理由でそのような機能や類似の機能が必要なので、私は回避策を提案します。
@Wanted
と@NotWanted
注釈を作成します。
@Component
@NotWanted
public class NotWantedService implements Service {}
と
:これらの新しい注釈を使用してBeanクラスに注釈を付ける
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Wanted {
}
と
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotWanted {
}
をこのよう
ApplicationContext applicationContext;
private <T> Collection<T> getBeansByTypeAndAnnotation(Class<T> clazz, Class<? extends Annotation> annotationType){
Map<String, T> typedBeans = applicationContext.getBeansOfType(clazz);
Map<String, Object> annotatedBeans = applicationContext.getBeansWithAnnotation(annotationType);
typedBeans.keySet().retainAll(annotatedBeans.keySet());
return typedBeans.values();
}
private <T> Optional<T> getBeanByTypeAndAnnotation(Class<T> clazz, Class<? extends Annotation> annotationType) {
Collection<T> beans = getBeansByTypeAndAnnotation(clazz, annotationType);
return beans.stream().findFirst();
}
をそして今、あなたはアノテーションで豆または1つのBeanを取得するためにそれらを使用することができますし、入力します:
@Component
@Wanted
public class WantedService implements Service {}
あなたはApplicationContext
へのアクセス権を持ってどこその後、あなたはどこかに2つの方法を追加する必要があります
Collection<Service> services = getBeansByTypeAndAnnotation(Service.class, Wanted.class);
または
Service service = getBeanByTypeAndAnnotation(Service.class, Wanted.class);
おそらくそれがBではありません問題に対処するための控えめな方法。しかし、我々は修飾子でApplicationContext
から豆を得ることができないので、 'out of box'と入力してください。これはこれを行う方法の1つです。
名前の定数、つまり 'ctx.getBean(" Wanted ")'を使用しているので、名前でBeanを取得しないのはなぜですか? – aux
@aux 'ctx.getBean(" service1 ")'を実行する場所が50あり、これを 'ctx.getBean(" service2 ")'に変更したいとします。それは50の変化です。修飾子を変更すると、2つのBean定義( 'service1'と' service2')のみに変更されます。他にも、「欲しい」複数の「サービス」インスタンスを取得したいとします。それらはすべて同じBean名を持つことはできません。 –
OK、わかりました。そして、あなたのbeanへの参照を保持し、spring-data-restの 'Repositories'のような異なるパラメータによる参照に使用する独自の"レジストリ "Beanを導入するのはどうでしょうか?またはラッパービーンですか? – aux