Java 如何在Spring中禁用使用@Component注释创建bean?
在我的项目中,我有一些重构逻辑的公共接口。看起来是这样的:Java 如何在Spring中禁用使用@Component注释创建bean?,java,spring,spring-boot,spring-annotations,Java,Spring,Spring Boot,Spring Annotations,在我的项目中,我有一些重构逻辑的公共接口。看起来是这样的: public interface RefactorAwareEntryPoint { default boolean doRefactor() { if (EventLogService.wasEvent(getEventType())) { return true; } boolean result = doRefactorInternal();
public interface RefactorAwareEntryPoint {
default boolean doRefactor() {
if (EventLogService.wasEvent(getEventType())) {
return true;
}
boolean result = doRefactorInternal();
if (result) {
EventLogService.registerEvent(eventType);
}
return result;
}
String getEventType();
boolean doRefactorInternal();
}
然后,当我需要编写一些重构时,我用方法实现这个接口,标记类,比如@Component
,然后Spring-in-loop评估每个接口实现并将其注册到数据库中。
但是我们有很多重构(每年——200-300个新的)。手动禁用旧的实现是很困难的,我们的spring上下文中有很多bean。
我们能做些什么吗,例如,使用一些注释-这将在某些条件下禁用组件创建
例如:
@Component
@Enabled(YEAR.2020)
public class CustomRefactor implements RefactorAwareEntryPoint {
// Code implementation
}
此注释的工作方式如下(伪代码):
当它将是
年.2021
-我们将从年.2020
在春季上下文中没有bean。查看BeanFactoryPostprocessor接口。可能您可以在创建bean之前删除它
否则,您可能会实现自己的BeanFactory并使用您的实现创建ApplicationContext。您可以使用spring boot提供的excludeFilter注释。使用注释
@Profile
,使应用程序配置和Bean在某些环境中可用
你可以在
Spring概要文件提供了一种隔离应用程序配置部分的方法,并使其仅在某些环境中可用。任何@Component、@Configuration或@ConfigurationProperties都可以标记为@Profile,以限制其加载时间
将每年视为一个单独的环境
@Component
@Profile("2020")
public class CustomRefactor2020 implements RefactorAwareEntryPoint {
// Code implementation
}
除了我们的同事提供的答案外,还要考虑弹簧的特性,称为“刻板注释”。这就是像
@Service
这样的著名注释在spring中的定义方式
通常,使用@Component
注释标记类这一事实允许您将类作为Springbean加载,因为被注释的类将成为一个名为“组件扫描”的过程的主题,该过程在启动应用程序上下文时发生
自Spring4以来,有一个条件接口,基本上可以实现类似于您所称的@Enabled(YEAR.2020)
的逻辑
您可以使用内置的“@conditionalnproperty”将2020年映射到属性,甚至可以实现一个。我假设您已经实现了一个自定义条件as@ConditionalOnYear
现在,有趣的是(这是我在文章开头提到的一个“刻板印象”特性),您可以使用自定义的“条件”逻辑创建自己的“组件”注释,并将其“当作”普通bean使用:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ConditionalOnYear(2020)
@Component
public @interface Year2020OnlyComponent {
@AliasFor(annotation = Component.class)
String value() default "";
}
您还可以通过巧妙地使用@AliasFor
注释来改进这一点,例如:
@SinceYearComponent(2020)
public class CustomRefactor implements RefactorAwareEntryPoint {
// Code implementation
}
但这超出了这个问题的范围,所以我在这里只提到一个方向
当然,即使没有这个“刻板印象”注释特性,也可以按照您的建议仅使用两个注释:
@Component
@SinceYear(2020) // a custom conditional
public class CustomRefactor implements RefactorAwareEntryPoint {
// Code implementation
}
@Profile
注释
启用/禁用配置文件excludeFilter
配置文件对你有用吗?我同意这可能是实现他想要的最简单的方法。我们还可以实现org.springframework.context.annotation.Condition和这个使用条件来为context创建bean。
@Year2020OnlyComponent
public class CustomRefactor implements RefactorAwareEntryPoint {
// Code implementation
}
@SinceYearComponent(2020)
public class CustomRefactor implements RefactorAwareEntryPoint {
// Code implementation
}
@Component
@SinceYear(2020) // a custom conditional
public class CustomRefactor implements RefactorAwareEntryPoint {
// Code implementation
}