我编写了一个@ProfileAll
与标准注释非常相似的注释,但是如果所有@Profile
给定的配置文件当前都处于活动状态,则注释的配置、方法……仅由 spring 处理:
ProfileAll.java(注解)
import org.springframework.context.annotation.Conditional;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(ProfileAllCondition.class)
public @interface ProfileAll {
/** The set of profiles for which the annotated component should be registered. */
String[] value();
}
ProfileAllCondition.java(条件)
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;
class ProfileAllCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (context.getEnvironment() != null) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(ProfileAll.class.getName());
if (attrs != null) {
LinkedList<String> profilesActive = new LinkedList<>();
LinkedList<String> profilesNotActive = new LinkedList<>();
List<Object> values = attrs.get("value");
int count = 0;
for (Object value : values) {
for (String profile : ((String[]) value)) {
count++;
if (context.getEnvironment().acceptsProfiles(profile)) {
profilesActive.add(profile);
} else {
profilesNotActive.add(profile);
}
}
}
if (profilesActive.size() == count) {
return true;
} else {
return false;
}
}
}
return true;
}
}
如下使用它,例如:
@Profile({ "mysql", "cloud", "special" })
@Configuration
public class MySqlConfig {
...
只有当所有三个配置文件在启动时都处于活动状态时,才会处理 MySqlConfig。