@Autowired annotation can be added to the constructors, methods, parameters, properties, types of annotations. If there is argument constructor or annotation @Bean only one way into the reference, can not write @Autowired omitted.
1, property
@Autowired
MyService bbb;
2, the constructor
@Autowired
public MyAuto(MyService bbb) {
this.bbb = bbb;
}
// 或者去掉 @Autowired 也可以
public MyAuto(MyService bbb) {
this.bbb = bbb;
}
3, method
@Autowired
public void setBbb(MyService bbb) {
this.bbb = bbb;
}
@Autowired automatically find the order of Bean
- Find @Qualifier according to specified Bean name
- If not specified @Qualifier, then find the notes according to @Primary
- If no @Primary, put the property name as Bean name lookup
- If you have not found, according to the type of search, if there are multiple types of the same category, can not be found, an error
Designated @Qualifier
@Autowired
@Qualifier("bbb")
MyService xx;
Specify @Primary
public interface MyService {}
@Service
@Primary
class Aaa implements MyService {}
@Service
class Bbb implements MyService {}
@Service
class Ccc implements MyService {}
How to choose injection method
Spring officially recommended to use constructor injection method, citing the original words:
The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not null. Furthermore, constructor-injected components are always returned to the client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.
Roughly translated means:
Use constructor injection, you can declare a variable as final, and to ensure that dependent object is not null, moreover, constructor injection to ensure the object initialization is complete. And if there are a lot of constructor parameters, it may require that the code reconstructed.