简单的说,就是当Spring容器扫描到某个接口的多个 bean 时,如果某个bean上加了@Primary 注解 ,则这个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,所以它将优先JdbcFooRepository被注入到 FooService中。这在大量应用组件扫描时经常出现。
转载于:https://www.cnblogs.com/hzhuxin/p/10980021.html