SoFunction
Updated on 2025-03-08

About the use of @Autowired and precautions

@Autowired Notes

Simply put, on the premise that the type is correct, first look based on the name, and then look based on the type if it is not found.

Examples are as follows:

If there is a bean in the container, the type of the bean isidWith the marked@AutowiredThe type and name of the attribute or method parameter are the same, then@AutowiredEquivalent to

@Autowired
@Qualifier("Attribute Name")

For example:

An interface existsTestInterfaceThere are two implementation classes:TestClass1andTestClass2All are in the spring container, there is aSomeClassThe class needs to be injectedTestInterfaceproperty

The code is as follows:

@Component
@Slf4j
public class SomeClass {

    @Autowired
    //This method will report an error because there are two beans of type TestInterface.    private TestInterface testInterface;
    
	//There will not be an error, because it is equivalent to	/*
	@Autowired
	@Qualifier("testClass1")
	*/
	@Autowired
	private TestInterface testClass1;

    public TestInterface getTestClass() {
        return testClass1;
    }
}

Can be added to a component@Primary, Force this type to use, for example

@Component
@Primary
public class TestClass2 implements TestInterface {
    private String s="testClass2";

    public String getS() {
        return s;
    }
}

So

@Autowired
	private TestInterface testClass1;

testClass1The type at this time isTestClass2

@Autowired where

1. Put it in front of the attribute, for examplecontrollerLayer callserviceLayer, will not be called before adding propertiessetmethod

@RestController
@RequestMapping("/student/card")
public class CardController {
    @Autowired
    CardService cardService;
}

2. PutsetBefore the method, it will be calledsetMethod assigns values ​​to attributes

@RestController
@RequestMapping("/student/card")
public class CardController {
    
    CardService cardService;
    
    @Autowired
    public void setCardService(CardService cardService) {
         = cardService;
    }
}

3.Written insetIn the parameter list of the method: only@BeanThe form, (can not be written, it will default@Autowired) and by default injected by name, equivalent to

public SomeClass someClass(@Autowired @Qualifier("card") Card card)
	@Bean
    public SomeClass someClass(@Autowired Card card){
        SomeClass someClass=new SomeClass();
        (card);
        return someClass;
    }
    
    @Bean
    public Card card(){
        Card card=new Card();
        ("01");
        return card;
    }

Injected by name

Use simultaneously@Autowiredand@Qualifier("beanName")

	@Autowired
    @Qualifier("beanName")
    private MybatisCardMapper mapper;

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.