在用spring框架开发中, 我们会遇到一种场景, 如果满足一个条件就装配一个bean,如果不满足就不装配该bean, 这种场景不太多, 但是也会用到
做法如下
一、之前我们用Java config 装配一个bean
package com.souche.erpinterface.server.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.souche.erpinterface.server.entity.vo.DicVO;
@Configuration
public class BeanDemo {
@Bean
public DicVO createBean () {
System.out.println("===========this is a createBean test==========");
DicVO vo = new DicVO();
return vo;
}
}
Spring 4.0中提供了 @Conditional 注解
package com.souche.erpinterface.server.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import com.souche.erpinterface.server.entity.vo.DicVO;
@Configuration
public class BeanDemo {
@Bean
@Conditional(MyCondition.class)
public DicVO createBean () {
System.out.println("==========this is a createBean test=========");
DicVO vo = new DicVO();
return vo;
}
}
在注解中提供一个MyCondition ,这个类很简单, 需要实现Condition接口, 实现matches方法,在方法中返回你的判断结果,true 或者 false,
package com.souche.erpinterface.server.config;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class MyCondition implements Condition{
@Override
public boolean matches(ConditionContext arg0, AnnotatedTypeMetadata arg1) {
return false;
}
}
如果返回true ,就会装配这个bean,如果返回false 则不装配这个bean