Top Description Methods
org.springframework.context.annotation

public @Interface Primary

extends Annotation
Annotations
@Target:TYPE, METHOD
@Retention:RUNTIME
@Documented
Imports
java.lang.annotation.Documented, .ElementType, .Retention, .RetentionPolicy, .Target

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.

This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.

May be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean.

Example

@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) {
        // ...
    }
}

Because HibernateFooRepository is marked with @Primary, it will be injected preferentially over the jdbc-based variant assuming both are present as beans within the same Spring application context, which is often the case when component-scanning is applied liberally.

Note that using @Primary at the class level has no effect unless component-scanning is being used. If a @Primary-annotated class is declared via XML, @Primary annotation metadata is ignored, and <bean primary="true|false"/> is respected instead.

Authors
Chris Beams, Juergen Hoeller
Since
3.0
See Also
Lazy, Bean, ComponentScan, org.springframework.stereotype.Component

Method Summary

Inherited from java.lang.annotation.Annotation:
annotationTypeequalshashCodetoString