SpringBoot-属性文件properties形式
上述使用JavaBean的配置可以实现数据源的配置,但是如果配置文件中的内容需要被多次调用就没那么方便了,所以我们学习新的方法,将Properties文件中的属性映射到类中的属性
SpringBoot中使用Java方式配置步骤如下:
创建一个名为application.properties <必须>的文件
将jdbc.properties中的内容放入application.properties 中
创建一个Java类例如JDBCProperties,加入@ConfigurationProperties注解(此注解拥有一个prefix属性,可以指定前缀)
在此类中声明的属性必须和Properties文件中的属性名一致(如果有前缀则为前缀点后的属性名)
此类需要提供getter、setter方法用于注入属性,可以使用lombok
在其他类中就可以直接使用此类中的属性了
packagecn.rayfoo.config;
importlombok.Data;
importorg.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author 张瑞丰
* @description
* @date 2019/11/4
*/
@ConfigurationProperties(prefix="jdbc")
@Data
publicclassJDBCProperties{
privateStringurl;
privateStringdriver;
privateStringusername;
privateStringpassword;
}
优化Java配置代码
在上一篇文章中,我们介绍了JavaBean配置的方法,这里我们优化一下其代码
去掉@PropertiesSource注解
新增@EnableConfigurationProperties注解,在其属性中指定JDBCProperties的字节码
去掉此类中的四个属性
使用@Autowired注解注入JDBCProperties类
在数据源中使用jdbcProperties类实例的getter方法
packagecn.rayfoo.config;
importcom.alibaba.druid.pool.DruidDataSource;
importlombok.Data;
importlombok.ToString;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.boot.context.properties.EnableConfigurationProperties;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.PropertySource;
importjavax.sql.DataSource;
/**
* @author 张瑞丰
* @description
* @date 2019/11/4
*/
@Configuration
@EnableConfigurationProperties(JDBCProperties.class)
publicclassJDBCConfig{
@Autowired
privateJDBCPropertiesjdbcProperties;
@Bean
publicDataSourcedataSource(){
DruidDataSourcedruidDataSource=newDruidDataSource();
druidDataSource.setUsername(jdbcProperties.getUsername());
druidDataSource.setPassword(jdbcProperties.getPassword());
druidDataSource.setUrl(jdbcProperties.getUrl());
druidDataSource.setDriverClassName(jdbcProperties.getDriver());
returndruidDataSource;
}
}