Spring Annotations @Qualifier detailed analysis

1 Overview

Today you look with Spring Framework @Qualifiernotes, what problems it solves, and how to use it. We also understand it @Primaryis different notes at. More technical analysis please visit felord.cn

2. pain points

Use @Autowiredannotations are Spring great dependency injection method. But some scenes alone enough to make this comment Spring know in the end what you want to inject bean . By default, @Autowiredaccording to the type of assembly the Spring Bean . If there are a plurality of the same type of vessel bean , the framework will be thrown NoUniqueBeanDefinitionExceptionto alert a plurality of conditions are satisfied bean automatic assembly. Program can not make the right judgments which one to use, here is a vivid example:

    @Component("fooFormatter")
    public class FooFormatter implements Formatter {
        public String format() {
            return "foo";
        }
    }

    @Component("barFormatter")
    public class BarFormatter implements Formatter {
        public String format() {
            return "bar";
        }
    }

    @Component
    public class FooService {
        @Autowired
        private Formatter formatter;
        
        //todo 
    }
复制代码

If we try to FooServiceload into our context, the Spring framework will be thrown NoUniqueBeanDefinitionException. This is because Spring did not know what to inject bean . To avoid this problem, there are several solutions. So we have to explain the paper @Qualifiernotes is one of them. Follow the rhythm of small fat brother go down.

3. @Qualifier

By using @Qualifierannotations, which we can eliminate the need to inject bean issue. Let's revisit the previous example, by including a look at how we @Qualifiercome out that we want to use annotations which bean to solve the problem:

    @Component
    public class FooService {
        @Autowired
        @Qualifier("fooFormatter")
        private Formatter formatter;
        
        //todo 
    }
复制代码

By @QualifierNotes and we want to use a specific Spring bean assembled together names, Spring framework can from several of the same type and meet assembly requirements of bean find what we want, avoid Spring split brain. We need to do is @Component or value property @Bean annotation statement to determine the name. In fact, we can also Formatteruse the implementation class @Qualifiernotes, instead of @Componentor @Beanin designated name, can achieve the same effect:

     @Component
     @Qualifier("fooFormatter")
     public class FooFormatter implements Formatter {
         public String format() {
             return "foo";
         }
     }
 
     @Component
     @Qualifier("barFormatter")
     public class BarFormatter implements Formatter {
         public String format() {
             return "bar";
         }
     }
复制代码
  1. @Qualifier VS @Primary there is another called @Primaryannotations, we can also be used to determine which dependency injection to inject ambiguity occurs when the bean . When there is more of the same type of bean time, this annotation defined preferences. Unless otherwise specified, we will use the @Primaryannotation associated bean . Let's look at an example:
    @Bean
    public Employee tomEmployee() {
        return new Employee("Tom");
    }

    @Bean
    @Primary
    public Employee johnEmployee() {
        return new Employee("john");
    }
复制代码

In this example, two methods are the same return Employeetype. Spring the injected bean method johnEmployeereturns bean . This is because it contains @Primaryannotations. When we want to specify default should be injected into a specific type of bean when this comment useful. If we need another injection at some point bean , we need to specifically point out it. We can @Qualifierdo this comment. For example, we can use @Qualifierto specify that we want to use annotation tomEmployeemethod returns the bean . It is noteworthy that, if @Qualifierand @Primaryannotations are present, then @Qualifierthe comment will have priority. Basically, @Primaryit defines default values, but @Qualifieris very specific. Of course, @Componentalso you can use @Primaryannotations, or 3 above example of the use of:

     @Component
     @Primary
     public class FooFormatter implements Formatter {
         public String format() {
             return "foo";
         }
     }
 
     @Component
     public class BarFormatter implements Formatter {
         public String format() {
             return "bar";
         }
     }
复制代码

In this case, the @Primaryannotation specifies the default injection is FooFormattereliminated inject ambiguity in the scene.

The name is automatically injected through

In use @Autowiredwhen automated assembly, if Spring no other tips, will need to be injected in accordance with the variable name to find the right bean . Dependency injection can also solve the problem of ambiguity. Let's look at some examples based on our initial code:

    @Component
    public class FooService {
        @Autowired
        private Formatter fooFormatter;
        
        //todo 
    }
复制代码

In this case, the Spring determined to be injected bean is FooFormatterbecause the field name in our bean 's @Componentor @Beanvalues used annotation (default @Beanmethod name) matches.

6. Summary

By @Qualifierexploring, we know the dependency injection annotations are used to eliminate the conflict. This in everyday development, such as Rabbtimq very common queue declared. Fat brother also showed some small common usage by the combination and Comparative annotations and other annotations of the above. This will help you to Spring understanding of dependency injection mechanism.

关注公众号:Felordcn获取更多资讯

Personal blog: https: //felord.cn

Guess you like

Origin juejin.im/post/5e0adfaa6fb9a0482806d826