JAVA项目使用手动多数据源配置文件方式引入数据源增加mybatis-plus的配置
mybatis引入之后 使用配置文件注入的方式 这时候我们再增加mybatis-plus配置的时候是不生效的 所以要把下面代码改写一下
以下参考mybatis-plus框架源码的MybatisPlusAutoConfiguration.java类
@Bean(name = "dcSqlSessionFactory") // 表示这个数据源是默认数据源 @Primary // @Qualifier表示查找Spring容器中名字为test1DataSource的对象 public SqlSessionFactory dcSqlSessionFactory(@Qualifier("dcDataSource") DataSource datasource, @Qualifier("applicationContext") ApplicationContext applicationContext) throws Exception { MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean(); bean.setDataSource(datasource); //数apper文件 Resource[] jarResources = new PathMatchingResourcePatternResolver().getResources("classpath*:mapperxml/*.xml"); Resource[] localResources = new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*/*.xml"); Resource[] resourcesAll = Stream.concat(Arrays.stream(localResources), Arrays.stream(jarResources)) .toArray(Resource[]::new); bean.setMapperLocations( // 设置mybatis的xml所在位置 resourcesAll ); //设置实体类映射规则: 下划线 -> 驼峰 如果需要 MybatisConfiguration configuration = new MybatisConfiguration(); configuration.setMapUnderscoreToCamelCase(true); bean.setConfiguration(configuration); // TODO 此处必为非 NULL GlobalConfig globalConfig = GlobalConfigUtils.defaults(); // TODO 注入填充器 this.getBeanThen(MetaObjectHandler.class, globalConfig::setMetaObjectHandler,applicationContext); // TODO 注入主键生成器 this.getBeansThen(IKeyGenerator.class, i -> globalConfig.getDbConfig().setKeyGenerators(i),applicationContext); // TODO 注入sql注入器 this.getBeanThen(ISqlInjector.class, globalConfig::setSqlInjector,applicationContext); // TODO 注入ID生成器 this.getBeanThen(IdentifierGenerator.class, globalConfig::setIdentifierGenerator,applicationContext); // TODO 设置 GlobalConfig 到 MybatisSqlSessionFactoryBean bean.setGlobalConfig(globalConfig); return bean.getObject(); }
/** * 检查spring容器里是否有对应的bean,有则进行消费 * * @param clazz class * @param consumer 消费 * @param <T> 泛型 */ private <T> void getBeanThen(Class<T> clazz, Consumer<T> consumer, ApplicationContext applicationContext) { if (applicationContext.getBeanNamesForType(clazz, false, false).length > 0) { consumer.accept(applicationContext.getBean(clazz)); } } /** * 检查spring容器里是否有对应的bean,有则进行消费 * * @param clazz class * @param consumer 消费 * @param <T> 泛型 */ private <T> void getBeansThen(Class<T> clazz, Consumer<List<T>> consumer, ApplicationContext applicationContext) { if (applicationContext.getBeanNamesForType(clazz, false, false).length > 0) { final Map<String, T> beansOfType = applicationContext.getBeansOfType(clazz); List<T> clazzList = new ArrayList<>(); beansOfType.forEach((k, v) -> clazzList.add(v)); consumer.accept(clazzList); } }
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网如果有地址失效了,可以私信我,后续看到会补充)