通过实现 EnvironmentAware 接口获取配置信息
参考:
EnvironmentAware 接口定义:
public interface EnvironmentAware extends Aware {
void setEnvironment(Environment environment);
}
- 所有的配置信息,都会加载到 Environment 实体中,因此我们可以通过这个对象来获取系统的配置;
- 凡是被 Spring 管理的类,实现接口 EnvironmentAware 接口重写 setEnvironment 方法,该方法中可以在工程启动时,获取到 Environment。
比如 SpringBoot 整合 MyBatis
application.properties 文件配置:
datasource.driverClassName=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost:3306/my-project?characterEncoding=utf8&serverTimezone=UTC
datasource.username=root
datasource.password=123456
配置类:
@Configuration
public class MyBatisConfig implements EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(final Environment environment) {
this.environment = environment;
}
/**
* 创建数据源(数据源的名称:方法名取为 XXXDataSource() 则 XXX 为数据库名称,该名称也就是数据源的名称)
*/
@Bean
public DataSource druidDataSource() throws Exception {
Properties props = new Properties();
props.put("driverClassName", environment.getProperty("datasource.driverClassName"));
props.put("url", environment.getProperty("datasource.url"));
props.put("username", environment.getProperty("datasource.username"));
props.put("password", environment.getProperty("datasource.password"));
return DruidDataSourceFactory.createDataSource(props);
}
/**
* 根据数据源创建 SqlSessionFactory
*/
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
// 指定数据源
fb.setDataSource(druidDataSource());
fb.setTypeAliasesPackage("com.project.domain");
// 指定 mapper 文件
fb.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return fb.getObject();
}
}