maybe a better question to ask is what is the best way to structure code like the above?
The Resolver class is used in a rest service (not shown). I also realize that the Resolver won't work as currently written. I am refactoring our legacy code and trying to understand the best way to structure our code with spring. When creating classes that utilize repositories, is it better to inject the repositories in the constructor and then move the previous constructor code into a method, and then call this new method in the method you want to call (resolveIdentifier method above)?
If the logic (without any Spring stuff) is something like this, where service creates a Resolver instance and then uses it:
and there is only one repository and Resolver always uses that same repository, I feel a cleaner design is to make Resolver a stateless singleton:
The spring version of that should be straightforward. Basically, remove the constructor argument and logic, move them to a getIdentifier or similar method and don't store that bcid in the Resolver.
But if that is not possible and Resolver has to to be one instance per request for some reason, then some changes have to be made:
1. Resolver should be made a "prototype" bean. In spring, beans are singletons by default; in contrast, a prototype bean is one that can be instantiated multiple times.
Every instance will be wired with dependencies.
2. The service bean should ask Spring to give it an instance of the Resolver. This can be done in multiple ways:
Via applicationContext, the downside being your code is now spring aware:
Via @Lookup annotation, the downside being your project has to include cglib.jar as a dependency:
Via javax.inject.Provider, the downside being your project has to include javax.inject jar as a dependency: