@Autowired
私は、基本的に春のドキュメントの例を使用して、きめ細かい構成を実装しようとしています: http://docs.spring.io/spring/docs/3.2.0.RELEASE/spring-framework-reference/html/beans.html #beans-autowired-annotation-qualifiers .
次のテストケースがあるとします。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ExampleConfiguration.class)
public class ExampleTest {
@Autowired @ExampleQualifier(key="x")
private ExampleBean beanWithQualifierKeyX;
@Test
public void test() {
System.out.println(this.beanWithQualifierKeyX);
}
}
および次の構成:
@Configuration
public class ExampleConfiguration {
@Bean
@ExampleQualifier(key = "x")
public ExampleBean exampleBean1() {
return new ExampleBean();
}
@Bean
@ExampleQualifier(key = "y")
public ExampleBean exampleBean2() {
return new ExampleBean();
}
@Bean
public ExampleBean exampleBean3() {
return new ExampleBean();
}
}
カスタム修飾子アノテーションを使用:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ExampleQualifier {
String key();
}
私が期待することは次のとおりです。プロパティbeanWithQualifierKeyX
は、構成クラスの最初の Bean を使用して自動配線する必要があります。構成の注釈とプロパティの注釈の両方にkey="x"
設定があるため、これだけが一致するはずです。私が見る限り、これはMovieQualifier
Spring サンプル ドキュメントのアノテーションとほぼ同じです。
ただし、テストを実行すると、次のエラーが発生します。
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private xxx.ExampleBean xxx.ExampleTest.beanWithQualifierKeyX;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [xxx.ExampleBean] is defined:
expected single matching bean but found 2: [exampleBean1, exampleBean2]
Spring はアノテーションに対して一致を実行するように見えますが ( と の両方exampleBean1
にアノテーションexampleBean2
が付けられているため)、アノテーションの値は考慮されていません。key
それ以外の場合x
は完全に一致します。
構成プロセスで何かを見逃していましたか、それとも一致しないのはなぜですか?
私が使用しているSpringのバージョンは3.2.0.RELEASEです