0

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?

Sri
  • 573
  • 2
  • 6
  • 20

1 Answers1

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