Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring framework 4.3.0 - when do i need @Autowired?

Tags:

java

spring

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?

like image 215
Tu Anh Avatar asked Dec 19 '22 16:12

Tu Anh


2 Answers

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

like image 111
reos Avatar answered Jan 06 '23 19:01

reos


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.

like image 25
dunni Avatar answered Jan 06 '23 18:01

dunni