在需要将配置文件的数据直接生成bean时,可以使用@ConfigurationProperties注解。
例如配置文件中有变量数据如下
spring.datasource.druid.maxActive=50
spring.datasource.druid.initialSize=1
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxWait=60000
spring.datasource.druid.timeBetweenEvictionRunsMillis=50000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.validationQuery=select 1
spring.datasource.druid.validationQueryTimeout=3
spring.datasource.druid.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.url=jdbc:mysql://gate.local.jed.jddb.com:3306/xstore_crowd?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8
spring.datasource.druid.username=xstore_crowd_admin
spring.datasource.druid.password=rLdLFisuIc1MwBJV
spring.datasource.druid.driverClassName=com.mysql.jdbc.Driver
@ConfigurationProperties有如下两种使用方式。个人倾向于第一种使用方式,此时可以支持使用多个不同配置,生成多个bean。
1.在生成bean时使用
@Setter
@Getter
public class DataSourceProperties {
/**
* 连接数据库的url
*/
private String url;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 数据库驱动,可不配置使用url自动识别
*/
private String driverClassName;
/**
* 初始化时建立的物理链接个数
*/
private Integer initialSize;
/**
* 最小连接池数量
*/
private Integer minIdle;
/**
* 最大连接池数量
*/
private Integer maxActive;
/**
* 连接时最大等待时间,单位毫秒
* 配置了maxWait后,缺省启用公平锁,并发效率会有所下降
* 如果需要可以通过配置useUnfairLock属性为true使用非公平锁
*/
private Integer maxWait;
/**
* destory线程检测连接的间隔时间
* 如果空闲时间大于等于minEvictableIdleTimeMills则关闭物理连接
* 如果testWhileIdle为true,申请连接的时候检测,
* 如果空闲时间大于timeBetwEvictionRunsMills,执行validationQuery检测是否有效
*/
private Integer timeBetweenEvictionRunsMillis;
/**
* 连接保持空闲而不被驱逐的最小时间,单位ms
*/
private Integer minEvictableIdleTimeMillis;
/**
* 默认值为false。建议配置为true。
* 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMills,执行validationQuery检测连接是否有效
*/
private boolean testWhileIdle;
/**
* 默认值为true,申请连接时执行validationQuery检测连接是否有效
*/
private boolean testOnBorrow;
/**
* 默认值为false。归还连接时执行validationQuery检测连接是否有效
*/
private boolean testOnReturn;
/**
* 用来检测连接是否有效的sql,要求是一个查询语句,常用select "X",
* 如果validationQ为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用
*/
private String validationQuery;
/**
* 单位s,检测连接是否有效的超时时间
*/
private Integer validationQueryTimeout;
/**
* 单位s,检测连接是否有效的超时时间
*/
private String filters;
}
@Slf4j
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.springboot.data.dao.repository"})
public class MybatisDbConfiguration {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DataSourceProperties getDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "dataSource")
public DataSource dataSource() {
DataSourceProperties properties = getDataSourceProperties();
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(properties.getDriverClassName()); //数据库驱动,如果不配置,会根据ur'自动识别
dataSource.setUrl(properties.getUrl()); //连接数据库的url
dataSource.setUsername(properties.getUsername()); //数据库用户名
dataSource.setPassword(properties.getPassword()); //数据库密码
dataSource.setInitialSize(properties.getInitialSize()); //数据库初始连接
dataSource.setMinIdle(properties.getMinIdle()); //数据库最小连接数
dataSource.setMaxActive(properties.getMaxActive()); //默认值为8,最大连接池数量
dataSource.setMaxWait(properties.getMaxWait()); //单位ms,获取连接时最大等待时间
dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); //destory线程检测连接的间隔时间
dataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); //单位ms,连接保持空闲不被驱逐的最小时间
dataSource.setTestWhileIdle(properties.isTestWhileIdle()); //默认值为false,申请连接时检测
dataSource.setTestOnBorrow(properties.isTestOnBorrow()); //申请连接时执行validationQuery检测连接是否有效
dataSource.setTestOnReturn(properties.isTestOnReturn()); //归还连接时执行validationQuery检测连接是否有效
dataSource.setValidationQuery(properties.getValidationQuery()); //用来检测连接是否有效的sql
dataSource.setValidationQueryTimeout(properties.getValidationQueryTimeout()); //单位s,检测连接是否有效的超时时间
try {
dataSource.setFilters(properties.getFilters()); //配置扩展插件
} catch (SQLException exception) {
log.error("MybatisDbConfiguration -> dataSource exception", exception);
}
return dataSource;
}
@Bean(name = "platformTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "transactionTemplate")
public TransactionTemplate transactionTemplate(@Qualifier("platformTransactionManager") PlatformTransactionManager platformTransactionManager) {
return new TransactionTemplate(platformTransactionManager);
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/*.xml"));
org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
config.setMapUnderscoreToCamelCase(true);
factoryBean.setConfiguration(config);
return factoryBean.getObject();
}
@Bean(name = "sqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2.在实体类上使用
@ConfigurationProperties(prefix = "spring.datasource.druid")
@Component
@Setter
@Getter
public class DataSourceProperties {
/**
* 连接数据库的url
*/
private String url;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 数据库驱动,可不配置使用url自动识别
*/
private String driverClassName;
/**
* 初始化时建立的物理链接个数
*/
private Integer initialSize;
/**
* 最小连接池数量
*/
private Integer minIdle;
/**
* 最大连接池数量
*/
private Integer maxActive;
/**
* 连接时最大等待时间,单位毫秒
* 配置了maxWait后,缺省启用公平锁,并发效率会有所下降
* 如果需要可以通过配置useUnfairLock属性为true使用非公平锁
*/
private Integer maxWait;
/**
* destory线程检测连接的间隔时间
* 如果空闲时间大于等于minEvictableIdleTimeMills则关闭物理连接
* 如果testWhileIdle为true,申请连接的时候检测,
* 如果空闲时间大于timeBetwEvictionRunsMills,执行validationQuery检测是否有效
*/
private Integer timeBetweenEvictionRunsMillis;
/**
* 连接保持空闲而不被驱逐的最小时间,单位ms
*/
private Integer minEvictableIdleTimeMillis;
/**
* 默认值为false。建议配置为true。
* 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMills,执行validationQuery检测连接是否有效
*/
private boolean testWhileIdle;
/**
* 默认值为true,申请连接时执行validationQuery检测连接是否有效
*/
private boolean testOnBorrow;
/**
* 默认值为false。归还连接时执行validationQuery检测连接是否有效
*/
private boolean testOnReturn;
/**
* 用来检测连接是否有效的sql,要求是一个查询语句,常用select "X",
* 如果validationQ为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用
*/
private String validationQuery;
/**
* 单位s,检测连接是否有效的超时时间
*/
private Integer validationQueryTimeout;
/**
* 单位s,检测连接是否有效的超时时间
*/
private String filters;
}
@Slf4j
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.springboot.data.dao.repository"})
public class MybatisDbConfiguration {
public DataSourceProperties getDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "dataSource")
public DataSource dataSource() {
DataSourceProperties properties = getDataSourceProperties();
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(properties.getDriverClassName()); //数据库驱动,如果不配置,会根据ur'自动识别
dataSource.setUrl(properties.getUrl()); //连接数据库的url
dataSource.setUsername(properties.getUsername()); //数据库用户名
dataSource.setPassword(properties.getPassword()); //数据库密码
dataSource.setInitialSize(properties.getInitialSize()); //数据库初始连接
dataSource.setMinIdle(properties.getMinIdle()); //数据库最小连接数
dataSource.setMaxActive(properties.getMaxActive()); //默认值为8,最大连接池数量
dataSource.setMaxWait(properties.getMaxWait()); //单位ms,获取连接时最大等待时间
dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); //destory线程检测连接的间隔时间
dataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); //单位ms,连接保持空闲不被驱逐的最小时间
dataSource.setTestWhileIdle(properties.isTestWhileIdle()); //默认值为false,申请连接时检测
dataSource.setTestOnBorrow(properties.isTestOnBorrow()); //申请连接时执行validationQuery检测连接是否有效
dataSource.setTestOnReturn(properties.isTestOnReturn()); //归还连接时执行validationQuery检测连接是否有效
dataSource.setValidationQuery(properties.getValidationQuery()); //用来检测连接是否有效的sql
dataSource.setValidationQueryTimeout(properties.getValidationQueryTimeout()); //单位s,检测连接是否有效的超时时间
try {
dataSource.setFilters(properties.getFilters()); //配置扩展插件
} catch (SQLException exception) {
log.error("MybatisDbConfiguration -> dataSource exception", exception);
}
return dataSource;
}
@Bean(name = "platformTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "transactionTemplate")
public TransactionTemplate transactionTemplate(@Qualifier("platformTransactionManager") PlatformTransactionManager platformTransactionManager) {
return new TransactionTemplate(platformTransactionManager);
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/*.xml"));
org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
config.setMapUnderscoreToCamelCase(true);
factoryBean.setConfiguration(config);
return factoryBean.getObject();
}
@Bean(name = "sqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}