5

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?

Synesso
  • 34,066
  • 32
  • 124
  • 194

1 Answers1

5

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.

chkal
  • 5,532
  • 18
  • 26
  • this implementation is in case of using feature toggles useless because your implementation will be discovered once since it is provided as singleton – vvursT Mar 24 '14 at 06:44
  • FeatureProxyFactoryBean will create a proxy which will dispatch method calls to the correct instance. So this will work fine. – chkal Mar 26 '14 at 12:53
  • This method declares to return a FeatureProxyFactoryBean, but you return a SystemClock. Won't this cause a ClassCastException? – Luis Muñiz Feb 19 '16 at 12:17
  • Thanks. Just fixed this. – chkal Feb 20 '16 at 08:13