标签:cond 第三章 nts override list port loader runner 属性
在使用的时候,某些bean需要在某些特定条件化才能实例化,spring中使用的@Condition注解实现这个功能。
1.接口
package main.java.soundsystem; public interface CompactDisc { void play(); }
2.实现
package main.java.soundsystem; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("dev") public class SgtPepper implements CompactDisc { private String title ="Sgt. Pepper‘s Lonely Hearts Club Band"; private String artist="The Beatles"; @Override public void play() { System.out.println("Playing "+ title +" by "+artist); } }
3.增加Condition实现类,需要实现Condition接口的matches方法,
方法返回true,表示使用这个条件的bean满足条件可创建,返回false,表示条件不满足,无法创建
package main.java.soundsystem; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class SgtPepperCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return true; } }
ConditionContext是一个接口,大致如下
public interface ConditionContext { BeanDefinitionRegistry getRegistry(); ConfigurableListableBeanFactory getBeanFactory(); Environment getEnvironment(); ResourceLoader getResourceLoader(); ClassLoader getClassLoader(); }
通过ConditionContext可以做到如下几点:
4.配置增加条件
package main.java.soundsystem; import org.springframework.context.annotation.*; @Configuration //@ComponentScan public class CDPlayerConfig { @Bean @Conditional(SgtPepperCondition.class) @Profile("dev") public CompactDisc sgtPeppers() { return new SgtPepper(); } }
5.测试
package main.java.soundsystem; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {CDPlayerConfig.class}) @ActiveProfiles("dev") public class CDPlayerTest { @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); cd.play(); } }
标签:cond 第三章 nts override list port loader runner 属性
原文地址:http://www.cnblogs.com/lvjianwei/p/7464571.html