We have summarized how to set Dependency Injection for Spring Framework.
By default, packages in the same hierarchy as the package of the class with @ComponentScan
are scanned. If you want to scan other classes, specify the package name in scanBasePackage
.
// @It can also be specified in compound annotations such as SpringBootApplication.
@ComponentScan(scanBasePackages={"com.example"})
Define the dependent object as a member of private`` final
, and define the constructor that receives the dependent object as an argument in the constructor. When using Lombok, it can be described as follows.
@Component
class ComponentA { ...
@RequiredArgsConstructor
class ClassA {
// @Autowired can be omitted.
private final ComponentA componentA;
...
Previously, it was mainstream to specify @Autowired
for non-final
members or their Setters.
class ClassA {
@Autowired
private ComponentA componentA;
...
class ClassA {
private ComponentA componentA;
@Autowired
public void setComponentA(ComponentA componenA) {
...
This is currently recommended because using the constructor has the following advantages:
--Become a module that can be used without DI. (The dependency can be set in the constructor on the user side.)
--You can add the final
qualifier. (The variable that stores the DI object is not usually rewritten.)
Since it is a Java standard, it is easy to switch to another DI container.
@Named //Or@ManagedBean
class ComponentA { ... }
Specify @Inject
in the constructor (or Setter). (Setter is also acceptable.)
@RequiredArgsConstructor(onConstructor=@__(@Inject))
class ClassA {
private final ComponentA componentA;
...
Alternatively, specify @Inject
as a member.
class ClassA {
@Inject
private ComponentA componentA;
...
Recommended Posts