Pages

Conditional bean

We have a bean in our application, but we want it instantiated only if some condition applies. To do that, we can use the Spring Conditional annotation, and let the framework decide if it has to be created or not.

Firstly, I create a very simple class in the restfun package:
public class MagicBean {
    @Override
    public String toString() {
        return "Magic Bean!";
    }
}
Then I create a class that implements the Condition Spring interface defining its matches() method.
public class MagicExistsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        return !env.containsProperty("lack_of_magic");
    }
}
I am saying that the condition hold when the environment does not contain the property named lack_of_magic.

And here is a configuration class that is putting all together in its method annotated as Conditional Bean, that specify the Condition class to verify if there is the condition for acting and that returns a new instance of the required class.
@Configuration
public class MagicConfig {
    @Bean
    @Conditional(MagicExistsCondition.class)
    public MagicBean magicBean() {
        return new MagicBean();
    }
}
To check if my magic bean works as expected, I have created a test case where I get it through both the Spring application context and directly by autowiring the specific bean.
@Test
public void testBeanInContext() {
    MagicBean mb = (MagicBean) context.getBean("magicBean");
    assertThat(mb.toString(), is("Magic Bean!"));
}

@Test
public void testBeanWired() {
    assertThat(magic.toString(), is("Magic Bean!"));
}
I played a bit around this code, changing the Condition and the tests, and enjoing the JUnit green light.
Until I felt satisfied, and I pushed the code to GitHub. See the source package and the JUnit test class for details.

I have written this post while reading the third chapter, Advanced wiring, of Spring in Action, Fourth Edition by Craig Walls. I ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of using the classic xml configuration. You should expect a few other minor changes in this code, basically because I wanted to have some fun too.

No comments:

Post a Comment