Search code examples
springtogglz

Togglz with Spring @Configuration bean


I'm trying to implement Togglz & Spring using @Configuration beans rather than XML. I'm not sure how to configure the return type of the Configuration bean. For example:

@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;
    }
}

The systemClock method returns a FeatureProxyFactoryBean but the clients of this bean require a SystemClock. Of course, the compiler freaks over this.

I imagine it just works when XML config is used. How should I approach it when using a configuration bean?


Solution

  • I'm not an expert for the Java Config configuration style of Spring, but I guess your systemClock() method should return a proxy created with the FeatureProxyFactoryBean. Something like this:

    @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();
    }
    

    But I'm not sure if this is the common way to use FactoryBeans with Spring Java Config.