5

使用SpringBootCondition更自由地定义条件化配置

 3 years ago
source link: https://www.pkslow.com/archives/springbootcondition
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
技术之前,先读诗书:

清明暮春里,怅望北山陲。

1 条件化配置

Spring提供了多种实现化条件化配置的选择,如ConditionalOnPropertyConditionalOnClass等。

用法如下:

@ConditionalOnProperty(prefix = "pkslow", name = "service", havingValue = "larry")
@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)

但有时候我们需要更灵活的自定义条件配置,这时可以通过继承SpringBootCondition类来实现。

2 继承SpringBootCondition

自己根据需求实现自己的判断逻辑,我的实现如下:

public class PkslowCondition extends SpringBootCondition {
  @Override
  public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    BindResult<List<String>> maxBindResult = Binder.get(context.getEnvironment()).bind("pkslow.condition.max", Bindable.listOf(String.class));
    BindResult<List<String>> minBindResult = Binder.get(context.getEnvironment()).bind("pkslow.condition.min", Bindable.listOf(String.class));

    if ( (maxBindResult.isBound() && !maxBindResult.get().isEmpty()) && (minBindResult.isBound() && !minBindResult.get().isEmpty()) ) {
      List<String> maxs = maxBindResult.get();
      List<String> mins = minBindResult.get();
      int max = Integer.parseInt(maxs.get(0));
      int min = Integer.parseInt(mins.get(0));

      if (max < 1000 && min > 0) {
        return ConditionOutcome.match();
      }

    }

    return ConditionOutcome.noMatch("pkslow.condition.max/pkslow.condition.min not matches");
  }
}

表示需要有配置属性pkslow.condition.max/pkslow.condition.min才会生效,并且要求max<1000min>0

完成自定义的条件类后,就可以使用它来限定一个配置类是否要生效了,使用如下:

@Conditional(PkslowCondition.class)
@Configuration
public class PkslowConfig {
    @PostConstruct
    public void postConstruct() {
        System.out.println("PkslowConfig called");
    }
}

代码请查看:https://github.com/LarryDpk/pkslow-samples


参考:springboot之使用SpringBootCondition


欢迎关注微信公众号<南瓜慢说>,将持续为你更新...

推荐阅读:
如何制定切实可行的计划并好好执行
容器技术(Docker-Kubernetes)
SpringBoot-Cloud相关
Https专题


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK