通过配置文件中的不同条件来执行特定的操作。

首先在application.properties配置属性:

is_load_bean=true
my.component.enabled=false

创建示例类UseConditionalOnProperty:

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UseConditionalOnProperty {
    @Value("${is_load_bean}")
    private String isLoadBean;

    @Bean
    @ConditionalOnProperty(value = "is_load_bean",havingValue = "true",matchIfMissing = true)
    public void loadBean() {
        log.info("是否加载当前类");
    }

    @Bean
    public void compareLoadBean(){
        log.info("加载bean属性:" + isLoadBean);
    }
}

运行结果:
11.png

创建条件类MyComponentCondition

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class MyComponentCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String property = context.getEnvironment().getProperty("my.component.enabled");
        return "true".equalsIgnoreCase(property);
    }
}

示例类MyComponent

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

@Component
@Conditional(MyComponentCondition.class)
@Slf4j
public class MyComponent {
    private final String test = "test";

    @Bean
    public void showTest() {
        log.info("This is " + test);
    }
}

运行结果:
12.png

标签: none

评论已关闭