标签:factory 连接 读取 word query 参考 enc com throw
项目开发中,我们有时想把配置文件的信息,读取并自动封装成实体类,这样子,我们在代码里面使用就方便多了。我们可以使用@ConfigurationProperties,把配置信息自动封装成实体类使用。其中配置信息可以放在配置文件中或者配置中心,例如Nacos。
liaowenhui.datasource:
validationQuery: SELECT 1
jdbcUrl:jdbc:mysql://192.168.xx.xx:3306/xxx?useUnicode=true&characterEncoding=UTF-8
jdbcUserName: liaowenhui
jdbcUserPassword: liaowenhui
//从配置信息中搜索前缀为liaowenhui.datasource的信息,读取并自动封装成实体类
@ConfigurationProperties(prefix = "liaowenhui.datasource") public class DataSourceProperties {
private String validationQuery; private String jdbcUrl; private String jdbcUserName; private String jdbcUserPassword; public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } public String getJdbcUserName() { return jdbcUserName; } public void setJdbcUserName(String jdbcUserName) { this.jdbcUserName = jdbcUserName; } public String getJdbcUserPassword() { return jdbcUserPassword; } public void setJdbcUserPassword(String jdbcUserPassword) { this.jdbcUserPassword = jdbcUserPassword; } }
@Configuration
@EnableConfigurationProperties({DataSourceProperties.class })
public class DataSourceConfig { private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class); @Bean(destroyMethod = "close") @RefreshScope public DataSource dataSourcePgProduct(DataSourceProperties dataSourceProperties) throws SQLException { logger.debug("数据库连接信息:{} ", dataSourceProperties.getJdbcUrl()); DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(dataSourceProperties.getJdbcUrl()); dataSource.setUsername(dataSourceProperties.getJdbcUserName()); dataSource.setPassword(dataSourceProperties.getJdbcUserPassword()); dataSource.setValidationQuery(dataSourceProperties.getValidationQuery()); ...... dataSource.init(); return dataSource; }
说明: @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入,但是@EnableConfigurationProperties注解不是一定要使用的,可以直接使用@Autowired DataSourceProperties dataSourceProperties进行注入,如果不用@EnableConfigurationProperties的话,实体类中除了要加@ConfigurationProperties还要加上@Component才能把配置信息注入IOC容器中。
可参考:关于@EnableConfigurationProperties 注解
spring boot中@ConfigurationProperties的使用
标签:factory 连接 读取 word query 参考 enc com throw
原文地址:https://www.cnblogs.com/liaowenhui/p/11203296.html