在多模块的项目中,我在 common公共模块新建 RedisTemplate的配置Bean 提供给其它模块直接使用redis进行操作。

运行时就发现

image

The bean 'redisTemplate', defined in class path resource [vip/xiwi/ziti/common/config/RedisTemplateConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class] and overriding is disabled.

大概意思是说:无法注入我们自己写的这个bean[vip/xiwi/ziti/common/config/RedisTemplateConfiguration.class];他已经在[org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class]这里定义了具有该名称的Bean。并且你的项目中禁止了bean覆盖。

既然是禁止了bean覆盖。那想当然就是设置下允许bean覆盖就可以嘛

修改项目配置文件,把允许bean覆盖的配置开一下
spring.main.allow-bean-definition-overriding=true
作用:设置为true时,后面定义的bean会覆盖之前定义的相同名称bean
问题虽是解决了,但如果是多人开发合作的时候,难以避免某些相同bean被定义覆盖,会出现很多不可思议的问题。
假设你又定义了其它相同bean,有一些相同的bean你只想某一个bean先加载怎么办。这里引入了第二种解决方案

加注解@AutoConfigureBefore
在bean类上加上 @AutoConfigureBefore注解,看源码可以知道可接收一个 Class[]数组。
注解@AutoConfigureBefore
@AutoConfigureBefore:我要在这些类前面加载
@AutoConfigureAfter:我要在这些类后面加载