Make a note of the technique used by seniors at work
Postscript: All were posted on this blog http://pppurple.hatenablog.com/entry/2016/12/29/233141
This is a convenient library that automatically generates boilerplate code (a standard code that cannot be omitted due to language specifications) at compile time. For example, JavaBean getters / setters can be annotated.
Suppose HogeLogic
is using FugaLogic
and you want to get it from a DI container.
Let's write a normal Spring constructor injection.
Sample A
@Component
public class HogeLogic {
private final FugaLogic fugaLogic;
@Autowired // <- 4.Can be omitted after 3
public HogeLogic(FugaLogic fugaLogic) {
this.fugaLogic = fugaLogic;
}
// some method
}
The important thing is that since ** spring4.3 you can omit @Autowired
if you have one constructor **.
Let's write the constructor injection omitted in Lombok.
Just annotate @RequiredArgsConstructor
to the class: angel:
Sample B
@RequiredArgsConstructor // <-here
@Component
public class HogeLogic {
private final FugaLogic fugaLogic;
// some method
}
Looking at the automatically generated code, it looks like this:
Sample C
@Component
public class HogeLogic {
private final FugaLogic fugaLogic;
public HogeLogic(FugaLogic fugaLogic) {
this.fugaLogic = fugaLogic;
}
// some method
}
The @Autowired
pear version of Sample A
is complete.
@RequiredArgsConstructor
Annotation to generate a constructor that has initialization parameters of fields that need to be initialized (such as final fields) as arguments. [TERASOLUNA Server Framework for Java (5.x) Development Guideline | 11.2. Elimination of Boilerplate Code (Lombok)](http://terasolunaorg.github.io/guideline/5.3.1.RELEASE/en/Appendix/Lombok .html)
The effect of @RequiredArgsConstructor
creates a constructor,
Since there is only one constructor, it means that @Autowired
is omitted.
The constructor was automatically injected ...
The combined technique is amazing.
Recommended Posts