I just start learning Spring framework (i use version 4.3.0) and i thought that we need @Autowired to tell the framework when a class need injection.
However, i try this today:
@Component
public class CDPlayer implements MediaPlayer{
private CompactDisc cd;
//there are no @Autowired here
public CDPlayer(CompactDisc cd) {
this.cd = cd;
}
public void play() {
cd.play();
}
}
and it work perfectly fine with automatic wiring configuration:
@Configuration
@ComponentScan
public class CDPlayerConfigAuto {
}
So when i do really need to use @Autowired?
Since Spring 4.3 this is not necesary if your class has only one constructor.
So as of 4.3, you no longer need to specify an explicit injection annotation in such a single-constructor scenario. This is particularly elegant for classes which otherwise do not carry any container annotations at all.
You can see here: (Implicit constructor injection for single-constructor scenarios)
https://spring.io/blog/2016/03/04/core-container-refinements-in-spring-framework-4-3
This is a new feature in Spring Boot 4.3. If you have only one constructor in the class, this constructor will be used to autowire the arguments. If you have more constructors or if you want to use setter or field injection, then you still need the @Autowired
annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With