我曾与不同的配置文件设置一个春天启动应用程序:dev
,prod
,qc
,console
等。
这两个配置类的设置如下。MyConfigurationA
应该为所有配置文件注册(除外)console
。MyConfigurationB
应该注册,但console
和除外dev
。
当我使用profile运行应用程序时console
,MyConfigurationA
不会被注册-很好。但是MyConfigurationB
得到注册-我不想要。我已@Profile
按如下所示设置了注释,以不注册MyConfigurationB
for资料console
和dev
。
但是MyConfigurationB
当我使用profile运行应用程序时,正在注册console
。
@Profile({ "!" + Constants.PROFILE_CONSOLE , "!" + Constants.PROFILE_DEVELOPMENT })
该文档(http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Profile.html)提供了一个示例,其中包含一个配置文件,而排除另一个配置文件。在我的示例中,我排除了两个@Profile({"!p1", "!p2"}):
@Profile({“ p1”,“!p2”}),如果配置文件'p1'处于活动状态,或者如果配置文件'p2'未处于活动状态,则会进行注册。
我的问题是:我们如何跳过两个配置文件的配置注册?@Profile({"!p1", "!p2"})
正在执行OR操作。我们在这里需要AND操作。
代码 :
@Configuration
@Profile({ "!" + Constants.PROFILE_CONSOLE })
public class MyConfigurationA {
static{
System.out.println("MyConfigurationA registering...");
}
}
@Configuration
@Profile({ "!" + Constants.PROFILE_CONSOLE , "!" + Constants.PROFILE_DEVELOPMENT }) // doesn't exclude both, its OR condition
public class MyConfigurationB {
static{
System.out.println("MyConfigurationB registering...");
}
}
public final class Constants {
public static final String PROFILE_DEVELOPMENT = "dev";
public static final String PROFILE_CONSOLE = "console";
...
}
@Profile({"!console", "!dev"})
表示(无控制台)或(无开发者),如果您使用配置文件“控制台”运行应用程序,则为true。
为了解决这个问题,您可以创建一个自定义条件:
public class NotConsoleAndDevCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
return !environment.acceptsProfiles("console", "dev");
}
}
并通过@Conditional批注将条件应用于配置:
@Conditional(NotConsoleAndDevCondition.class)
public class MyConfigurationB {
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句