I am attempting to create a blueprint for modular, clean architectures. One of the principles that I want to follow is "all objects must be valid at all times".
Also, I am using the module system (java 11).
The problem is that I cannot inject dependencies of my services via their constructor, thus cannot respect the said principle.
Is there any non-obvious way to sneak in parameters via the constructor when using ServiceLoader
? I am fine with an isolated usage of reflection in Main
to accomplish this.
Alternatives that I've been thinking about:
- using another method akin to "initialize" which requires the dependencies. The problem with this, or any other setter-based approach is the temporal coupling between the call to this method and actually using the service; or in other words, violating the principle stated above
- making the "service" not an actual service, but a factory with only one method, which takes the dependencies via parameters, similar to the previous point. My issue with this approach is the accidental complexity created by doing this.
So far, my intention is to take the second approach, but I don't like the accidental complexity. Also, each service will offer multiple operations (meaning that the temporal coupling is a real thing in this case).
I am aware of the other question regarding this, but I am curious if it's possible with a newer java version and/or with with reflection.