简体   繁体   English

在Spring中无需使用ApplicationContext.getBean()即可动态自动装配bean

[英]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. 我有一个Servlet,它根据其中包含的人的地址对XML文件进行验证。 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: 我正在使用Spring,现在我正在使用以下内容获得正确的验证器:

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(). 似乎应该有一种更好的方法在运行时获取正确的bean,而不使用getBean()。 Does anyone have any suggestions? 有没有人有什么建议?

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. 您可以在Spring之前用所需的bean预填充地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM