参考https://github.com/zhey/multidatasource,未经过严格测试,仅供参考,请勿用于实际项目
原来做项目的过程中使用多数据源时都是有几个数据源就在Configuration标注的类中添加几个@Bean标注的Datasource,后来想自动配置多数据源yaml格式为:
multi:
datasources:
datasourc1:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo
username: demo
password: demo
datasourc2:
driver-class-name:
url:
username:
password:
mybatis:
mybatis1:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.zhey.entity
mybatis2:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.zhey.entity
最开始在子容器中使用ApplicationContext注入BeanDefinition,最开始运行正常,后来发现有些情况下就回报bean没有定义的异常,经过分析发现注入自定义的BeanDefinition时和所在的Configuration注解的类有关系,spring在扫描时会对扫描到的@Configuration注解的类按字母排序,所以如果有需要datasource的类在前面的话就会导致找不到bean。
解决思路就是在父容器中进行多数据源的初始化,这在springboot出现以前经常用到,就是在web.xml中配置listener和servlet,listener配置的是父容器,servlet配置的是子容器,我常将servie层以下放在父容器中配置,controller在子容器中配置。
在springboot中的配置过程为,在resources目录下创建META-INF文件夹,并创建spring.factories文件,在文件中添加配置如下:
org.springframework.context.ApplicationListener=\
com.zhey.parent.LocalApplicationListener
LocalApplicationListener
实现ApplicationListener<ApplicationEnvironmentPreparedEvent>
接口 在onApplicationEvent函数中创建一个springApplication,并通过ApplicationInitializer将创建的applicationContext添加到子容器中。
不知道如何传代码,有兴趣可以查看spring-cloud-context包下的BootstrapApplicationListener源码。
网友评论