Spring in action读书笔记(三) Spring Conditional注解应用-----条件化加载bean
假设有一个名为MagicBean的类,只有设置了magic环境属性的时候,Spring才会实例化这个类。这时可以使用@Conditional注解
package test.aop; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration public class MagicBeanConfig { @Bean @Conditional(MagicExistsCondition.class) public MagicBean magicBean() { return new MagicBean(); } static class MagicBean { private MagicBean() { } } }
@Conditional注解中给定了一个class,它指明了条件,@Conditional接口建通过Condition接口进行条件对比,MagicExistsCondition类实现如下:
package test.aop; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotatedTypeMetadata; public class MagicExistsCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment env = context.getEnvironment(); return env.containsProperty("magic"); } }
运行测试类,测试MagicBean能否被正确创建
package test.aop; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {MagicBeanConfig.class}) public class TestCondition { @Autowired(required = false) private MagicBeanConfig.MagicBean magicBean; @Test public void test() { Assert.assertNotEquals(magicBean, null); } }
增加JVM参数 -Dmagic=true 再测试 MagicBean能否被创建