@Condiitional根据条件判断是否加载该bean

@ Conditional

@Conditional进行条件判断: 符合条件则加载该bean,不符合则不加载该bean

实例

实现condition类

这个类是判断application.yaml中spring.profiles.active配置项是否为user

package run.halo.app.annotation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;


@Slf4j
public class DevCondition implements Condition{

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //获取当前环境信息
        Environment environment = context.getEnvironment();

        //获得配置文件
        String active = environment.getProperty("spring.profiles.active");

        // context 代表Ioc容器  context.getBeanFactory 从Ioc容器里获取容器工厂
        //调用该容器工厂,添加判断条件

        log.info("active {}",active);
        if(active=="dev"){
            return false;
        }
        return true;
    }
}

注:这个里面不能用@Value获取配置文件的值,获取不到,因为是在 @Conditional调用的,没有用@AutoWired

配置

如果DevCondition.class返回true则加载这个bean否则不加载

 	@Bean
    @Conditional(DevCondition.class)
    public TomcatServletWebServerFactory servletContainer() {

        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×