Is it mandatory to put @Autowired
if I am using constructor DI?
In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.
Here the quote from the official documentation : 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.
Spring container looks at the beans on which autowire attribute is set constructor in the XML configuration file. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans.
In the spring boot, the @Autowired annotation must be used in the constructor with more than one argument. Each argument needs to load a bean different from the ApplicationContext spring boot. The annotation can not be specified in the constructor, as only one bean name can be specified.
Is @Autowired annotation mandatory for a constructor?
No.
After Spring 4.3 If your class has only single constructor then there is no need to put @Autowired
.
Before Spring 4.3:
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
After:
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
Extra: With Lombok, after Spring 4.3
With Lombok you can use @RequiredArgsConstructor
to make the code even cleaner:
@Service
@RequiredArgsConstructor
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
}
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