@Conditional
根据某个条件来决定是否创建Bean实例
代码下载地址:http://download.csdn.net/download/poiuy1991719/9965794
创建一个Bean类:
package com.bean.conditional; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component; @Component("magicBeanName")//重命名:配置类里面的方法与之对应 @Conditional(MagicCheck.class)//决定是否创建Bean的条件类 public class MagicBean { private String name="MagicBean"; public MagicBean() { System.out.println("MagicBean:实例化"); } public void showName(){ System.out.println("Show Name is:"+name); } }
创建一个Config配置类:配置类指定了一个Check类:
package com.bean.conditional; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages={"com.bean"}) public class BeanConfigs { @Bean @Conditional(MagicCheck.class)//决定是否创建Bean对象 public MagicBean magicBeanName(){//方法名来源,Bean类的注解:@Component("magicBeanName") return new MagicBean(); } }
Check类决定是否创建Bean的实例:Check类需是Condition类的一个实现:
package com.bean.conditional; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; //决定Bean的创建,需是Condition的一个接口 public class MagicCheck implements Condition { public boolean matches(ConditionContext arg0, AnnotatedTypeMetadata arg1) { return true;//创建Bean实例 // return false;//不创建Bean实例 } }
测试类:
package test; 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; import com.bean.conditional.BeanConfigs; import com.bean.conditional.MagicBean; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes={BeanConfigs.class}) public class test { @Autowired MagicBean mb; @Test public void selfTest(){ if(mb==null){ System.out.println("MagicCheck类决定了Bean的创建,MagicCheck类方法返回:false"); }else{ System.out.println("MagicCheck类决定了Bean的创建,MagicCheck类方法返回:true"); mb.showName(); } } }