【发布时间】:2019-08-19 14:00:17
【问题描述】:
我有一堆模块(比如 3 个)。两个是基于 Spring Boot 的模块,另一个是基于 Spring 的。 说模块 1 - SpringBoot 模块 2 - Spring Boot 模块 3 - 仅基于 Spring 的通用模块
Module 3 @Configuration 定义的文件只需要Module 2 而不是Module 1 选择。
我尝试了很多方法来排除配置文件。例如:-
@SpringBootApplication
@ComponentScan(basePackages = {"com.adobe"}
, excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {WorkerConfig.class, WorkerExecutors.class, Worker.class})})
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
但是@Configiration 类仍然没有被排除,Spring 正在尝试将它加载到我不想要的应用程序上下文中。我的配置类
@Configuration
public class WorkerConfig {
@Bean
public WorkerExecutors workerExec() {
WorkerExecutors executors = new WorkerExecutors();
return executors;
}
}
我也确实在@ComponentScan 注释中读到了
* <p>Note that the {@code <context:component-scan>} element has an
* {@code annotation-config} attribute; however, this annotation does not. This is because
* in almost all cases when using {@code @ComponentScan}, default annotation config
* processing (e.g. processing {@code @Autowired} and friends) is assumed. Furthermore,
* when using {@link AnnotationConfigApplicationContext}, annotation config processors are
* always registered, meaning that any attempt to disable them at the
* {@code @ComponentScan} level would be ignored.
所以看起来在组件扫描中排除是行不通的。除上述之外,我还尝试排除使用
@SpringBootApplication(exclude= {WorkerExecutors.class, Worker.class,WorkerConfig.class})
public class Application {
但是弹簧靴会抛出
java.lang.IllegalStateException: The following classes could not be excluded because they are not auto-configuration classes:
- com.adobe.repository.worker.lib.config.WorkerConfig
- com.adobe.acp.repository.worker.lib.core.WorkerExecutors
- com.adobe.acp.repository.worker.lib.core.Worker
知道如何禁用组件扫描弹簧引导模块中的非弹簧引导模块,而不是放入不同的包中。我不想放入不同的包装中。
感谢任何帮助!
【问题讨论】:
-
一种有点老套的方法是为
Worker配置提供@ConditionalOnProperty注释,然后仅为模块2 设置属性。 -
是的,这行得通..我使用条件而不是属性条件,因为它带来了我想避免的 spring boot 依赖..但是你说它很hacky?
-
这有点骇人听闻,因为 - 正如在其他一些 cmets 中所提到的,您最好将模块拆分,以便只有需要在类路径上的代码实际上在类路径上(即模块 1 甚至不应该能够访问模块 3) 的不需要的配置类。通过像这样使用“分段”组件扫描,您可能会在路上遇到错误/问题,毕竟来自 Worker 确实的东西需要出现在模块 1 中,并迫使您重新设计这种方法.但是,如果它对您有用并且您可以处理这些问题,那么它也是一种方法。
-
同意这一点。但是现在它是一个单独的类,所以将它们移出类路径没有多大意义。但是,是的,当这样的事情增加时,代码肯定会变得错误且难以维护。
标签: java spring spring-boot