Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to ApplicationContext.getBean() in Spring

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.

like image 336
Sayak Mukhopadhyay Avatar asked Oct 18 '25 11:10

Sayak Mukhopadhyay


1 Answers

Since Spring 4.3 you can autowire all implementations into a Map consisting of pairs beanName <=> beanInstance:

public class APIHandler {

    @Autowired
    private Map<String, SomeInterface> impls;

    public ResponseEntity post(@RequestBody HandlingClass requestBody) {
        String beanName = "..."; // resolve from your requestBody        
        SomeInterface someInterface = impls.get(beanName);
        someInterface.doSomething();
    }
}

assuming you have two implementations like following

// qualifier can be omitted, then it will be "UseClass1" by default
@Service("beanName1") 
public class UseClass1 implements SomeInterface { } 

// qualifier can be omitted, then it will be "UseClass2" by default
@Service("beanName2")
public class UseClass2 implements SomeInterface { } 
like image 84
Nikolai Shevchenko Avatar answered Oct 20 '25 00:10

Nikolai Shevchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!