我正在嘗試使用 Spring Boot 自動配置功能并遇到問題。我創建了一個 github 存盤庫,以便能夠輕松地重現“問題”:https ://github.com/clembo590/spring-auto-configuration
只需運行mvn clean install,您將獲得我在描述中參考的所有日志。
我已經“啟用”了debug=truespring boot 屬性以查看是否激活了哪個“自動配置”(如果它不活動,為什么它不活動)。
我還添加了一些日志來“記錄所有已添加到 Spring Boot 背景關系中的 bean”。
這是我的自動配置類。
@Configuration
@ComponentScan(basePackageClasses = MyClass.class)
@ConditionalOnBean(ObjectMapper.class)
@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
public class CleaningAutoConfiguration {
@Bean
public Fake fake(){
return new Fake();
}
private static class Fake{
}
}
第一個奇怪的事情是這個日志:
CleaningAutoConfiguration:
Did not match:
- @ConditionalOnBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) did not find any beans of type com.fasterxml.jackson.databind.ObjectMapper (OnBeanCondition)
Matched:
- @ConditionalOnBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found bean 'jacksonObjectMapper' (OnBeanCondition)
First question: Why is @ConditionalOnBean BOTH matching and Not matching ? (my expectation about such a condition is that it should either match or not match... but not both... see question 5)
Now if we look at the logs it seems that CleaningAutoConfiguration is in the Negative matches: section.
Second question:
why is CleaningAutoConfiguration itself registered as a bean ? (I was expecting it would not as it is in the Negative matches section).
Third question:
Why is fake still registered as a bean (I was expecting that fake would not be registered, and not even instanciated...)
Fourth question:
why is MyClass not registered as a bean ?
Now if you remove the @ComponentScan(basePackageClasses = MyClass.class) then all those questions go away as CleaningAutoConfiguration goes into Positive matches section, but one new is created:
第五個問題:為什么洗掉 @ComponentScan 會CleaningAutoConfiguration帶入Positive matchessection ?(也許問題 5 與問題 1 有某種聯系......?)
uj5u.com熱心網友回復:
問題的根本原因是在不支持@ComponentScan的自動配置類上使用:
此外,自動配置類不應啟用組件掃描以查找其他組件。
@Import應該使用特定的 s 來代替。
要回答您的具體問題:
為什么
@ConditionalOnBean既匹配又不匹配
它首先被評估為考慮不受支持的@ComponentScan注釋的一部分。此時,ObjectMapperbean 尚未定義,因此不匹配。隨后在ObjectMapperbean 被定義為匹配點之后對其進行評估。
為什么 CleaningAutoConfiguration 本身注冊為 bean ?(我期待它不會像在負匹配部分中那樣)。
由于正負匹配,報告在這里誤導了您。CleaningAutoConfiguration由于正匹配是一個bean。
為什么fake仍然注冊為bean(我原以為fake不會注冊,甚至沒有實體化......)
報告又誤導了你。條件CleaningAutoConfiguration已匹配,因此其Fakebean 已定義。
為什么
MyClass沒有注冊為bean
考慮注釋時,條件CleaningAutoConfiguration不匹配,因此未啟用 ' 包的組件掃描。@ComponentScanMyClass
為什么洗掉
@ComponentScan帶入CleaningAutoConfiguration正匹配部分
它可以防止在尚未定義 beanCleaningAutoConfiguration時過早評估條件。ObjectMapper當它們最終在預期的時間被評估時,ObjectMapperbean 存在并且條件匹配。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426034.html
