@TargetSE(valueSE={TYPESE,METHODSE}) @RetentionSE(valueSE=RUNTIMESE) @DocumentedSE public @interface Primary
このアノテーションは、Spring XML の <bean>
要素の primary
属性と意味的に同等です。
直接または間接的に @Component
でアノテーションが付けられたクラス、または @Bean
でアノテーションが付けられたメソッドで使用できます。
@Component public class FooService { private FooRepository fooRepository; @Autowired public FooService(FooRepository fooRepository) { this.fooRepository = fooRepository; } } @Component public class JdbcFooRepository extends FooRepository { public JdbcFooRepository(DataSource dataSource) { // ... } } @Primary @Component public class HibernateFooRepository extends FooRepository { public HibernateFooRepository(SessionFactory sessionFactory) { // ... } }
HibernateFooRepository
は @Primary
でマークされているため、両方が同じ Spring アプリケーションコンテキスト内の Bean として存在すると想定して、jdbc ベースのバリアントよりも優先的に注入されます。これは、コンポーネントスキャンが自由に適用される場合によく見られます。
コンポーネントスキャンが使用されていない限り、クラスレベルで @Primary
を使用しても効果がないことに注意してください。@Primary
アノテーション付きクラスが XML を介して宣言されている場合、@Primary
アノテーションメタデータは無視され、代わりに <bean primary="true|false"/>
が考慮されます。
Lazy
, Bean
, ComponentScan
, Component