Consider the following ways of doing Dependency Injection in a pseudo-singleton, by using Lombok‘s @ApplicationScoped
:
It will not work.
❌
@ApplicationScoped
public class MyService {
private final Database db;
@Inject
public MyService (final Database db) {
this.db= db;
}
...
}
^ That code will crash at startup because the DI engine demands a parameter-less constructor.
This one :
❌
@ApplicationScoped
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class MyService {
private final Database db;
}
^ …will crash at startup for the same reasons (missing parameter-less constructor)
I cannot do this :
❌
@ApplicationScoped
public class MyService {
@Inject
private Database db;
}
^ …because my unit tests need to be able to pass the db’s mock explicitly.
So, I try to add the parameter-less constructor:
⚠️
@ApplicationScoped
@RequiredArgsConstructor(onConstructor = @__(@Inject))
@NoArgsConstructor(force = true)
public class MyService {
private final Database db;
}
That works, but it makes the linter paranoid : It warns me that db
could be null wherever I use it.
I’m aiming at zero warnings. What’s the correct way of achieving that?
I’ve seen some examples where people added a “getInstance
” method that checks for null but my intuition is that there is a more straightforward/more compact solution that fits well with the annotations.