java - 定义自动配置的顺序不起作用

标签 java spring-boot

我有一个示例项目here 。在这个多模块项目中。我有模块promotion-service其中PromotionConfiguration依赖其他配置先完成。

@Configuration @AutoConfigureAfter({RulesConfiguration.class, PointsConfiguration.class}) public class PromotionConfiguration { @Bean public PromotionService promotionService(ObjectProvider<List<Rule>> rules) { System.out.println("Adding PromotionService to context"); List<Rule> ruleList = rules.getIfAvailable(); if (!ruleList.isEmpty()) { ruleList.sort(Comparator.comparingInt(Rule::getOrder)); } return new PromotionServiceImpl(ruleList); } }

但是当Spring Boot应用程序依赖于模块promotion-service时规则在促销服务启动后添加到上下文中

2018-02-18 11:20:26.743 INFO 11582 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] Adding PromotionService to context Adding PointRule to context. Adding PromotionRule to context. 2018-02-18 11:20:27.087 INFO 11582 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@196a42c3: startup date [Sun Feb 18 11:20:25 EST 2018]; root of context hierarchy

最佳答案

解析配置及其结构与在运行时有效创建 bean 之间存在差异。这里的具体问题是什么?

如果我运行你的项目,promotionService正如您所期望的那样,使用 2 条规则创建。如果我添加 @ConditionalOnMissingBean(Rule.class)promotionService它没有被创建(这证明上下文知道至少有一个 Rule bean 将被创建)。

您不必太担心运行时部分,上下文可以根据其优化计划自由调用必要的工厂方法(即 @Bean 带注释的方法)(即执行智能操作来解决周期)。

您获得此日志输出的原因是您没有要求上下文解析 Rule bean 。 ObjectProvider是一个代理,在您请求某些内容之前不会执行任何操作(在本例中为 getAvailable)。

我已将注入(inject)点更改为使用 List<Rule>我得到以下信息:

Adding PointRule to context.
Adding PromotionRule to context.
Adding PromotionService to context

所以一切都很好。但是请重命名您的自动配置,使其以 AutoConfiguration 结尾。而不是Configuration .

关于java - 定义自动配置的顺序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48853995/

相关文章:

java - 无法连接到 Google Play 服务;获取取消状态代码

java - 重复该程序,直到用户在数组中键入 none

使用 Spring Boot 对 Elasticsearch/AWS 进行 Java API 运行状况检查

java - 配置 Spring Batch JobScope 时调用 configprops 时出错

java - Springboot : startup issue(missing ServletWebServerFactory bean)

java - 在 Weblogic 中部署 Spring Boot 应用程序

java - 如何在我的 Android 应用程序中截取屏幕截图

java - 常量 MissingServletRequestParameterException

java - 对对象进行排序的数据结构

spring-boot - Kotlin + SpringBootTest + Junit 5 + AutoConfigureMockMvc:应该在失败时测试通过(似乎@BeforeEach无效)