@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 isid
With the marked@Autowired
The type and name of the attribute or method parameter are the same, then@Autowired
Equivalent to
@Autowired @Qualifier("Attribute Name")
For example:
An interface existsTestInterface
There are two implementation classes:TestClass1
andTestClass2
All are in the spring container, there is aSomeClass
The class needs to be injectedTestInterface
property
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;
testClass1
The type at this time isTestClass2
@Autowired where
1. Put it in front of the attribute, for examplecontroller
Layer callservice
Layer, will not be called before adding propertiesset
method
@RestController @RequestMapping("/student/card") public class CardController { @Autowired CardService cardService; }
2. Putset
Before the method, it will be calledset
Method assigns values to attributes
@RestController @RequestMapping("/student/card") public class CardController { CardService cardService; @Autowired public void setCardService(CardService cardService) { = cardService; } }
3.Written inset
In the parameter list of the method: only@Bean
The 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@Autowired
and@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.