Spring Framework learning (VIII): @ Qualifier for advanced assembly

During development, you certainly want to own procedures more intelligent, I mean automatic assembly. Earlier we talked about the special @Autowired notes can automatically get to meet the requirements in the context of the bean, and injected into the property you want to inject. Like this:

Examples of this content is to be done: the program is running, automatically injected into an object class Student student reference. The question is, if there are multiple bean objects are Student I now context, what happens? The answer is that the assembly failed, because we can imagine, because there are multiple objects that satisfy the condition, so the Spring did not know which one to select, result in an exception.

To solve this problem, we can use Spring's @Qualifier notes, see-known name meaning, @ Qualifier annotation is "limited" means. Look at the code.

@Configuration
@ComponentScan(basePackageClasses = MyConfig.class)
public class MyConfig {

    @Bean
    @Qualifier("work1")
    Homework homework1(){
        return new Homework("1+5 = ?");
    }

    @Bean
    @Qualifier("work2")
    Homework homework2(){
        return new Homework("2+6 = ?");
    }

}
@Component
public class Student {

    @Value("小明")
    private String name;

    //请看这里
    @Autowired
    @Qualifier("work2")
    private Homework homework;

    public Student(){}
    public Student(String name, Homework homework) {
        this.name = name;
        this.homework = homework;
    }

    public void doHomeWork(){
        System.out.println(homework.getContent());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Homework getHomework() {
        return homework;
    }

    public void setHomework(Homework homework) {
        this.homework = homework;
    }


}

I use when creating the bean @Qualifier annotation, when the injection is also used, the same parameters. This will not ambiguous, and automatic assembly would be normal. Recommended for use in the development process in such a way to indicate the bean to be assembled.

This one would share it here, if there are to help you, welcome thumbs up collection plus interest.

Guess you like

Origin www.cnblogs.com/chenyulin/p/11225093.html