Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring DI having two constructors at the same time

This is an anti pattern, but I am curious what will actually happen.

If you explicitly define a no-args constructor and a constructor with an autowired parameter, how exactly will spring framework initialize it?

@Service
class Clazz {

    private MyBean myBean;

    public Clazz(){}

    @Autowired
    public Clazz(MyBean myBean){
        this.myBean = myBean;
    }
}
like image 464
Bato-Bair Tsyrenov Avatar asked Oct 21 '25 17:10

Bato-Bair Tsyrenov


1 Answers

On top of above answers, if there is single constructor declared without @autowire, spring uses same constructor for injection.

If there multiple constructors, then Spring uses constructor which is @autowired.

Mentioned in Spring Doc https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#beans-autowired-annotation

As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean only defines one constructor to begin with. However, if several constructors are available, at least one must be annotated to teach the container which one to use

like image 165
Oomph Fortuity Avatar answered Oct 24 '25 07:10

Oomph Fortuity