简体   繁体   English

春天打电话给工厂自动接线

[英]Spring call a factory to autowire

Is there any way to have spring call a factory with a runtime parameter of the type of the parent class of a variable it is trying to autowire? 有什么方法可以让spring尝试自动装配变量的父类类型的运行时参数来调用工厂?

For example, let's say I have something like this: 例如,假设我有这样的事情:

interface IConfig {
}

interface IConfigProvider {

    IConfig getConfig(Class<?> type)
}

class MyClass {

    @Autowired
    private IConfig _config;
}

Is there anyway to have spring, when autowiring MyClass._config to essentially call IConfigProvider.getConfig(MyClass.class) (well the concrete version that is in the context) at runtime to wire the variable? 当在运行时自动装配MyClass._config以本质上调用IConfigProvider.getConfig(MyClass.class) (以及上下文中的具体版本IConfigProvider.getConfig(MyClass.class)时,总有弹簧吗?

I know I could autowire the factory and call it myself, I could even "hide" it in a base class but I am trying to avoid this. 我知道我可以为工厂自动布线并自己命名,甚至可以在基类中“隐藏”它,但我正在努力避免这种情况。

NOTE: I am very new to Spring so if I am asking something really stupid/not using the right terminology, I apologise. 注意:我对Spring还是很陌生,所以如果我问的是真的很愚蠢/不使用正确的术语,我深表歉意。

You would need to create a FactoryBean for that. 您将需要为此创建一个FactoryBean Something like this should do the trick. 这样的事情应该可以解决问题。

class IConfigFactoryBean implements FactoryBean<IConfig> {

    @Autowired
    private IConfigProvider configProvider;

    private IConfig config;

    @PostConstruct
    public void initialize() {
        config = configProvider.getConfig(...);
    }


    @Override
    public IConfig getObject() throws Exception {
        return config;
    }

    @Override
    public Class<?> getObjectType() {
        return ...;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

I am not sure what the argument would be. 我不确定会是什么。 Note that if you have several instances of IConfig you will need to qualify them as Spring won't be able to know which one it has to inject based on a simple @Autowired annotation. 请注意,如果您有多个IConfig实例,则需要对它们进行限定,因为Spring不能基于简单的@Autowired注释知道它必须注入哪个实例。 Check the javadoc of @Qualifier for more information. 检查@Qualifier的javadoc以获取更多信息。

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

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