mybatis-config.xml如何加载spring多环境配置?


application配置文件拆成了不同环境,
数据库的配置分配在application-dev.propertiesapplication-pro.properties文件中,启动项目后报错

### Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: ${spring.datasource.driver-class-name}] with root cause

我分析是mybatis配置文件的问题,
mybati-config.xml如何配置?

-------------------------------分割线-------------------------------------------

没人回答,自问自答吧:

controller

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    DemoService service;

    @RequestMapping("/test")
    public HashMap<String, Object> getTest() {
        return service.test();
    }
}

service

@Service
public class DemoService {
    @Autowired
    DemoMapper mapper;

    public HashMap<String, Object> test() {
        System.out.println(mapper.testXml());
        return mapper.test();
    }
}

mapper

public interface DemoMapper {
    @Select("select * from user where id=1")
    HashMap<String, Object> test();

    HashMap<String, Object> testXml();
}

application.properties

spring.profiles.active=prod
# 格式化全局时间字段
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
# 指定时间区域类型
spring.jackson.time-zone=GMT+8
# mybatis写sql语句的XML文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

application-dev.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=
# 数据库用户名&密码:
spring.datasource.username=
spring.datasource.password=
# 打印sql语句日志
logging.level.com.ace.xxx=DEBUG

application-prod.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=
# 数据库用户名&密码:
spring.datasource.username=
spring.datasource.password=

DemoMapper.xml

文件放在application.properties配置的路径/src/main/resources/mapper/DemoMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ace.order.mapper.DemoMapper">
    <select id="testXml" resultType="hashmap">
        select * from user where id = 2
    </select>
</mapper>

启动类

@SpringBootApplication
@MapperScan("com.ace.xxx.mapper")
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
阅读 2.5k
2 个回答

这都springboot了,还在坚持用这种配置文件? - -

spring:
profiles:

active: ${env}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题