Spring 4爲conditional bean creation帶來了一些很酷的功能。在你的情況下,確實普通@Profile
註釋是不夠的,因爲它使用OR
運算符。
您可以做的一個解決方案是爲其創建自定義註釋和自定義條件。例如
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional(NoProfilesEnabledCondition.class)
public @interface NoProfilesEnabled {
String[] value();
}
public class NoProfilesEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean matches = true;
if (context.getEnvironment() != null) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(NoProfileEnabled.class.getName());
if (attrs != null) {
for (Object value : attrs.get("value")) {
String[] requiredProfiles = (String[]) value;
for (String profile : requiredProfiles) {
if (context.getEnvironment().acceptsProfiles(profile)) {
matches = false;
}
}
}
}
}
return matches;
}
}
以上是ProfileCondition快速和骯髒的修改。
現在你可以註釋你的bean的方式:
@Component
@NoProfilesEnabled({"foo", "bar"})
class ProjectRepositoryImpl implements ProjectRepository { ... }