Spring 4为有条件的Bean创建带来了一些很酷的功能。在你的例子中,实际上普通的注释是不够的,因为它使用运算符。@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;
}
}
以上是配置文件条件的快速和肮脏的修改。
现在,您可以通过以下方式注释您的豆子:
@Component
@NoProfilesEnabled({"foo", "bar"})
class ProjectRepositoryImpl implements ProjectRepository { ... }