使用SpringBootCondition更自由地定义条件化配置
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.
清明暮春里,怅望北山陲。
1 条件化配置
Spring
提供了多种实现化条件化配置的选择,如ConditionalOnProperty
和ConditionalOnClass
等。
用法如下:
@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<1000
且min>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专题
- 本文作者: 南瓜慢说
- 本文链接: https://www.pkslow.com/archives/springbootcondition
- 版权声明: 本博客所有文章除特别声明外,不可转载!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK