Can we inject a bean to a service during runtime? I'm working on a Spring MVC application and have two different beans which use the same functionality. I need to inject a bean during runtime based on some parameters. How do I do that in Spring?
Asked
Active
Viewed 672 times
0
-
where is the code ? Add the code – Vasu Nov 09 '16 at 17:04
-
Possible duplicate of [Runtime dependency injection with Spring](http://stackoverflow.com/questions/1439839/runtime-dependency-injection-with-spring) – Witold Kaczurba Nov 09 '16 at 17:14
1 Answers
0
If you want to switch between the beans which are already created then use this method
Autowire ApplicationContext in the class
@Autowired ApplicationContext ctx;
And in the method, just get those beans from the ApplicationContext and switch between those. I would use an interface and then have those 2 (or more) classes (which you want to switch at runtime) implement the interface so that there will be a contract.
BeanInterface beanName;
if (x){
beanName = (BeanClass1) ctx.getBean("beanClass1");
}
else{
beanName = (BeanClass2) ctx.getBean("beanClass2");
}
Disclaimer: Did not test this out, you might need some tweaks if this is not working.
If you want even the bean creation to be based on certain runtime parameters, take a look here https://stackoverflow.com/a/34350983/6785908

Community
- 1
- 1

so-random-dude
- 15,277
- 10
- 68
- 113