我有一个示例项目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/