LucasP
LucasP

Reputation: 1715

Dynamically autowire a bean without using ApplicationContext.getBean() in Spring

I have a servlet that does validation on XML files based on the address of the person contained in it. The validation is specific to each state, so I have several implementations of my validator, but I don't know which one to use until the request is parsed each time.

I am using Spring, and right now I am getting the correct validator with the following:

Validator validator = applicationContext.getBean(this.state + "Validator");

This seems to break some of the inversion of control. I thought about moving this to a factory class that essentially does the same thing, but abstracts it to a factory:

@Component
public class ValidatorFactory {

    @Autowired
    ApplicationContext applicationContext;

    public Validator getValidator(String state) {
        return applicationContext.getBean(state + "Validator");
    }
}

It seems like there should be a better way to get the correct bean at runtime without using getBean(). Does anyone have any suggestions?

Upvotes: 1

Views: 1035

Answers (1)

Chetan Kinger
Chetan Kinger

Reputation: 15212

You can use a Map :

@Component
public class ValidatorFactory {

    @Autowired
    Map<String,Validator> validators;

    public Validator getValidator(String state) {
        return validators.get(state + "Validator");
    }
}

You can pre-populate the map with the required beans throughs Spring.

Upvotes: 2

Related Questions