Is there a way that I can define a "PostConstruct" initialization method with lombok?
@RequiredArgsConstructor(staticName = "of")
class MyObj {
private final int x;
private final int y;
private int z;
// not work
@PostConstruct
private void someInitLogic {
z = x + y;
}
public void start() {
// code use "z"
}
}
So that I can init an object like:
MyObj obj = MyObj.of(1, 2);
obj.start();
Since @PostConstruct is still an open issue and similar questions have popped up, I would like to suggest a workaround which could be followed if you have any of the below problems:
this.x=x
and replace all such constructors of the below form and with lombok.someInitLogic()
is a new method and the class is part of an API or there are lots of places were the constructor is being invoked. So you do not want to force any code changes in the callers.For anyone with the above issues, I suggest a workaround as follows:
Add a dummy
final
variable to your class. Make ittransient
if class isSerializable
.Make the access level in
@AllArgsConstructor
or@RequiredArgsConstructor
as private (even if you use astaticName
), so that the constructor with the dummy parameter is not accessible outside.or
Write a constructor or static method which matches with the one that is currently being invoked as below:
Or if you were using
static
method to invoke the constructor:This way you could reduce the boiler plate code, but at the same do not cause any code changes in the callers and could be easily refactored as soon as
@PostConstruct
is available.