我可以否定(!)一系列弹簧型材吗? [英] Can I negate (!) a collection of spring profiles?
问题描述
是否可以以一种不被一组配置文件使用的方式配置bean?目前我可以这样做(我相信):
Is it possible to configure a bean in such a way that it wont be used by a group of profiles? Currently I can do this (I believe):
@Profile("!dev, !qa, !local")
是否有更简洁的符号来实现这一目标?我们假设我有很多个人资料。另外,如果我有一个Mock和一些服务(或其他)的具体实现,我可以只注释其中一个,并假设另一个将用于所有其他情况?换句话说,这是必要的:
Is there a neater notation to achieve this? Let's assume I have lots of profiles. Also, if I have a Mock and concrete implementation of some service (or whatever), Can I just annotate one of them, and assume the other will be used in all other cases? In other words, is this, for example, necessary:
@Profile("dev, prof1, prof2")
public class MockImp implements MyInterface {...}
@Profile("!dev, !prof1, !prof2") //assume for argument sake that there are many other profiles
public class RealImp implements MyInterface {...}
我可以只注释其中一个,并坚持一个<相反,code> @Primary 注释?
Could I just annotate one of them, and stick a @Primary
annotation on the other instead?
本质上我想要这个:
@Profile("!(dev, prof1, prof2)")
提前致谢!
推荐答案
简短回答是:你做不到。
但由于 @Conditional
注释,存在整齐的解决方法。
Short answer is : You can't.
But there are neat workaround that exists thanks to the @Conditional
annotation.
public abstract class ProfileCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
if (matchProfiles(conditionContext.getEnvironment())) {
return ConditionOutcome.match("A local profile has been found.");
}
return ConditionOutcome.noMatch("No local profiles found.");
}
protected abstract boolean matchProfiles(final Environment environment);
}
public class DevProfileCondition extends ProfileCondition {
private boolean matchProfiles(final Environment environment) {
return Arrays.stream(environment.getActiveProfiles()).anyMatch(prof -> {
return prof.equals("dev") || prof.equals("prof1")) || prof.equals("prof2"));
});
}
}
public class ProdProfileCondition extends ProfileCondition {
private boolean matchProfiles(final Environment environment) {
return Arrays.stream(environment.getActiveProfiles()).anyMatch(prof -> {
return !prof.equals("dev") && !prof.equals("prof1")) && !prof.equals("prof2"));
});
}
}
使用
Use it
@Conditional(value = {DevProfileCondition.class})
public class MockImpl implements MyInterface {...}
@Conditional(value = {ProdProfileCondition.class})
public class RealImp implements MyInterface {...}
但是,这个方法需要Springboot。
However, this aproach requires Springboot.
这篇关于我可以否定(!)一系列弹簧型材吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!