I am using SpringBoot in my application and am currently using applicationContext.getBean(beanName,beanClass) to get my bean before performing operations on it. I saw in a couple of questions that it is discouraged to use getBean(). Since I am very new to Spring I don't know all the best practices and am conflicted. The solutions posed in the above linked question probably won't work in my use case. How should I approach this?
@RestController @RequestMapping("/api") public class APIHandler { @Value("${fromConfig}") String fromConfig; private ApplicationContext applicationContext; public Bot(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @PostMapping(value = "") public ResponseEntity post(@RequestBody HandlingClass requestBody) { SomeInterface someInterface = applicationContext.getBean(fromConfig, SomeInterface.class); someInterface.doSomething(); } } I have an interface called SomeInterface defined like:
public interface SomeInterface { void doSomething(); } And I have 2 classes which implements this interface called UseClass1 and UseClass2. My config file stores a string with the bean name of a class which I need to know in run-time and call the appropriate implementation of the method.
Any directions would be appreciated.
someInterfacesomeImpl? :)