Y
Y
Yasuro2019-09-30 10:55:24
Spring
Yasuro, 2019-09-30 10:55:24

How to parametrize springBoot bean on the fly?

There is a component:

@Component
public class Provider<EntityType> extends AbstractProvider<EntityType> {
    @Autowired
    private ApplicationContext appCxt;

    MyService<EntityType> myService;
}

I need to parametrize MyService depending on the request from the frontend. That is, MyService is initialized with one of the child classes. There are a lot of child classes, I don’t want to auto-brew all of them, so there is an ApplicationContext from which, by name, we get the desired child object:
public void initService(Class clazz) {
        final String entityClassName = clazz.getName();

        if (MyObjectService.class.getName.equals(entityClassName)){
            this.myService= appCxt.getBean(MyObjectService.class);
        }

Now I'm working with this API from the outside like this:
1) Provider autoware
2) Upon request from the front, I find out which service is needed.
3) I call the initService () method from the Provider, into which I pass the required child class
. I need the third step to be absent. Instead, I want the api user to get from the context ( appCxt.getBean(Provider.class) ) a bean with an initialized service. The question is how to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yerlan Ibraev, 2019-09-30
@mad_nazgul

1. Make all possible beans for MyService. Those. create implementations of all services. It is possible through xml or config class
2. Inject as List myServices
3. Search in myServices for the implementation you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question