繁体   English   中英

如何指定抽象类的具体实现的哪个版本在Spring中自动装配?

[英]How to specify which version of a concrete implementation for an abstract class to autowire in Spring?

具有以下类结构:

public abstract class A {
    String someProperty = "property"

    public abstract void doSomething();
}

@Service
public class Aa extends A {

    @Override
    public abstract void doSomething() {
        System.out.println("I did");
    }
}

@Service
public class Ab extends A {

    @Override
    public abstract void doSomething() {
        System.out.println("I did something else");
    }
}

我需要一种方法来告诉Spring A具体的类在我的Foo服务中基于属性文件中的属性Autowire

@Service
public class Foo {

    @Autowire
    private A assignMeAConcreteClass;
}

在我的properties文件中,我有这个:

should-Aa-be-used: {true, false}

删除@Service注释,而是在读取属性的配置类中编写@Bean -annotated方法 ,并返回相应的A实例。

不是一种新的方式,但在你的情况下,我认为一种可能的合适方式是在想要有条件地注入bean的类中使用FactoryBean
这个想法很简单:通过使用要注入的bean的接口FactoryBean进行参数化来实现FactoryBean ,并覆盖getObject()以注入所希望的实现:

public class FactoryBeanA  implements FactoryBean<A> {   

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${should-Aa-be-used}")
    private boolean shouldBeUsed;

    @Override
    public A getObject() {

        if (shouldBeUsed) {
            return applicationContext.getBean(Aa.class));

        return applicationContext.getBean(Ab.class));

    }
}

但是FactoryBean实例不是经典bean。 您必须专门配置它。

您可以通过以下方式在Spring Java配置中配置它:

@Configuration
public class FactoryBeanAConfiguration{

    @Bean(name = "factoryBeanA")
    public FactoryBeanA factoryBeanA() {
         return new FactoryBeanA();
    }

    @Bean
    public beanA() throws Exception {
        return factoryBeanA().getObject();
    }
}

暂无
暂无

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

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