Togglz与Spring @Configuration bean

时间:2013-02-27 06:56:13

标签: spring togglz

我正在尝试实施Togglz& Spring使用@Configuration bean而不是XML。我不确定如何配置Configuration bean的返回类型。例如:

@Configuration
public class SystemClockConfig {

    @Bean
    public SystemClock plainSystemClock() {
        return new PlainSystemClock();
    }

    @Bean
    public SystemClock awesomeSystemClock() {
        return new AwesomeSystemClock();
    }

    @Bean
    public FeatureProxyFactoryBean systemClock() {
        FeatureProxyFactoryBean proxyFactoryBean = new FeatureProxyFactoryBean();
        proxyFactoryBean.setActive(awesomeSystemClock());
        proxyFactoryBean.setInactive(plainSystemClock());
        proxyFactoryBean.setFeature(Features.AWESOME_SYSTEM_CLOCK.name());
        proxyFactoryBean.setProxyType(SystemClock.class);
        return proxyFactoryBean;
    }
}

systemClock方法返回FeatureProxyFactoryBean,但此bean的客户端需要SystemClock。当然,编译器对此感到不满。

我想它在使用XML配置时才有用。使用配置bean时应该如何处理它?<​​/ p>

1 个答案:

答案 0 :(得分:5)

我不是Spring的Java Config配置样式的专家,但我想你的systemClock()方法应该返回使用FeatureProxyFactoryBean创建的代理。像这样:

@Bean
public SystemClock systemClock() {
    FeatureProxyFactoryBean proxyFactoryBean = new FeatureProxyFactoryBean();
    proxyFactoryBean.setActive(awesomeSystemClock());
    proxyFactoryBean.setInactive(plainSystemClock());
    proxyFactoryBean.setFeature(Features.AWESOME_SYSTEM_CLOCK.name());
    proxyFactoryBean.setProxyType(SystemClock.class);
    return (SystemClock) proxyFactoryBean.getObject();
}

但我不确定这是否是将FactoryBeans与Spring Java Config一起使用的常用方法。