Autowiring two beans implementing same interface - how to set default bean to autowire?

前端 未结 5 633
南旧
南旧 2020-11-28 17:50

Background:

I have a Spring 2.5/Java/Tomcat application. There is the following bean, which is used throughout the application in many places

publi         


        
5条回答
  •  失恋的感觉
    2020-11-28 18:28

    The use of @Qualifier will solve the issue.
    Explained as below example : 
    public interface PersonType {} // MasterInterface
    
    @Component(value="1.2") 
    public class Person implements  PersonType { //Bean implementing the interface
    @Qualifier("1.2")
        public void setPerson(PersonType person) {
            this.person = person;
        }
    }
    
    @Component(value="1.5")
    public class NewPerson implements  PersonType { 
    @Qualifier("1.5")
        public void setNewPerson(PersonType newPerson) {
            this.newPerson = newPerson;
        }
    }
    
    Now get the application context object in any component class :
    
    Object obj= BeanFactoryAnnotationUtils.qualifiedBeanOfType((ctx).getAutowireCapableBeanFactory(), PersonType.class, type);//type is the qualifier id
    
    you can the object of class of which qualifier id is passed.
    

提交回复
热议问题