Spring's @Primary comment

Simply put, when the Spring container is scanned to an interface of multiple bean, if added @Primary annotation on a bean, then the bean will be preferred, as in the following 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 annotated @Primary HibernateFooRepository above, so it is injected into the priority JdbcFooRepository in FooService. This often occurs when a large number of application components scan.

Guess you like

Origin www.cnblogs.com/hzhuxin/p/10980021.html