pok*_*ken 2 java spring autowired
I got a project with tons of services and repositories. Currently each repository is autowired to a service using annotations.
@Service
public class Service1 {
@Autowired
private Repository1 repository1;
@Autowired
private Repository2 repository2;
...100+ more
}
Run Code Online (Sandbox Code Playgroud)
All of these repository are under the same package. Is it possible to skip declaration for each repository?
A simple solution I found would be to implement an interface like this:
@Autowired
private Map<String,RepositoryInterface> repositoryInterface
public void method1(){
repositoryInterface.get("repository1").doMethod();
}
Run Code Online (Sandbox Code Playgroud)
It should have been a good solution but problem is I don't have access to all the source codes. I have tons of repository classes that I am not allowed to change to add an interface class.
So is there another way to solve this? Like just scan the whole package and just use bean name to access the repositories?
Beans are retrievable from their class or their name (and both).
In your case, you could rely directly on their class to retrieve them from the context.
Inject an ApplicationContext (or constructor way) :
@Autowired
private ApplicationContext applicationContext;
Run Code Online (Sandbox Code Playgroud)
And use it :
applicationContext.getBean(RepositoryOne.class).doMethod1();
Run Code Online (Sandbox Code Playgroud)
Ideally it should be extracted into a method :
public <T> T getRepository(Class<T> clazz){
return applicationContext.getBean(clazz);
}
Run Code Online (Sandbox Code Playgroud)
to be used more simply :
getRepository(RepositoryOne.class).doMethod(1);
Run Code Online (Sandbox Code Playgroud)
But I would warn about needing so many field dependencies in a class.
This makes it very hard to maintain/to test and also very error prone to use.
The best thing to do is rethink your design to avoid such complex/bloat class.
Besides using structure like private Map<String,RepositoryInterface> repositoryInterface or ApplicationContext will make you lose the benefit from dependency checks performed by the Spring container at startup that prevents NullPointerException and errors related to inconsistency (dependency missing) during the application working.
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |