起因:在改造未曾謀面的同事的微服務遇到的尷尬問題,發現公共的基礎項目中已經配置了RedisConfig,本地的微服務項目中也配置這樣一個配置。
一、配置代碼如下
@Component
@EnableCaching
public class MyRedisConfig extends CachingConfigurerSupport {
//省略代碼
}
二、我的難題
錯誤信息
Caused by: java.lang.IllegalStateException: 2 implementations of
CachingConfigurer were found when only 1 was expected. Refactor
the configuration such that CachingConfigurer is implemented only
once or not at all. at
三、原由
spring中允許使用默認的cacheManager
,但是不允許同時存在兩個。
四、排除其他的
那就在啓動類上使用註解過濾不需要重複的文件,關鍵代碼如下。
@ComponentScan(
basePackages = {"com.xx"},
excludeFilters= {@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE,
classes= {com.xx.common.config.CacheConfig.class,com.xx.common.config.RedisConfig.class})})
其實也可以直接刪除自己維護項目中的配置,只是因爲不確定刪除之後會出現什麼狀態,所以我們選擇排除其他的配置。