Annotation @Autowired
Supposed that you have a Bean
, you can use @Autowired
to autowire the bean.
For example:
@Component
public class MyComponent {
...
}
@Configuration
public class MyConfiguration {
@Autowired
private MyComponent myComponent;
}
[!note]
Note that in here if you're using field auto-wired, the field cannot be final.
However, it's recommended to use Constructor injection:
@Configuration
public class MyConfiguration {
private final MyComponent myComponent;
public MyConfiguration(MyComponent myComponent) {
this.myComponent = myComponent;
}
}
If we have multiple constructor, we can then use @Autowired
to specify which constructor we want Spring to use
@Configuration
public class MyConfiguration {
private final MyComponent myComponent;
private final MyService myService;
@Autowired
public MyConfiguration(MyComponent myComponent) {
this.myComponent = myComponent;
}
public MyConfiguration(MyComponent myComponent, MyService myService) {
this.myComponent = myComponent;
this.myService = myService;
}
}