A preface

This article focuses on two important annotation ways and scenarios: @primary and @Qualifier annotations. This disambiguates bean injection and lets the Spring container know which bean to load;

Inheriting the spirit of open Source, Spreading technology knowledge;

Ii. Implementation Mode

In the following example, the Sheet interface is used and the implementation class is SheetA, SHeetB. Because the injected container is of Sheet type, exceptions may occur. In this case, @primary or @qualifier is used to restrict the injected bean to achieve normal injection.

2.1 Sheet Interface

/ * * *@AuthorLSC * < P > sheets </p> */
public interface Sheet {

    String getColor(a);
}
Copy the code

2.2 Sheet implementation classes

The implementation class a.

Override getColor(); The output of red

/ * * *@Author lsc
 * <p> </p>
 */
public class SheetA implements Sheet {


    public String getColor(a) {
        return "red"; }}Copy the code

The implementation class B

Override getColor(); Output pink


/ * * *@Author lsc
 * <p> </p>
 */
public class SheetB implements Sheet {



    public String getColor(a) {
        return "pink"; }}Copy the code

2.3 configuration class

@Configuration
public class SheetConfig {


    @Bean
    public Sheet sheetA(a){
        return new SheetA();
    }

    @Bean
    public Sheet sheetB(a){
        return newSheetB(); }}Copy the code

2.4 the test class


/ * * *@Author lsc
 * <p> </p>
 */
@RunWith(SpringJUnit4ClassRunner.class)// Create spring application context
@ContextConfiguration(classes= {SheetConfig.class})// Load the configuration class
public class SheetTest {

    @Autowired
    Sheet sheet;

    @Test
    public void sheetTest(a){
        //System.out.println(sheet.getColor()); }}Copy the code

The test will report an exception because two sheets have been injected into the Spring container. It is impossible to distinguish SheetA from SheetB, causing bean ambiguity.

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException:
Copy the code

Solution 1

Add the @primary annotation to the injected bean; In this example, add the @primary annotation to sheetB and spring will inject beans with the @Primary annotation first. The test output is PINK

    @Bean
    @Primary
    public Sheet sheetB(a){
        return new SheetB();
    }
Copy the code

Solution 2

Add the @Qualifier annotation when injecting beans to qualify the injected beans. The output is red

    @Qualifier("sheetA")// qualify the injected Bean ID
    @Autowired
    Sheet sheet;
Copy the code