1、application.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/leyou
jdbc.username=root
jdbc.password=123
2、JdbcProperties文件
package cn.itcast.springboot.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
//属性读取类
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
private String driverClassName;
private String url;
private String username;
private String password;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在类上通过@ConfigurationProperties注解声明当前类为属性读取类,prefix="jdbc"读取属性文件中,前缀为jdbc的值。
在类上定义各个属性,名称必须与属性文件中jdbc.后面部分一致,并且必须具有getter和setter方法
需要注意的是,这里我们并没有指定属性文件的地址,SpringBoot默认会读取文件名为application.properties的资源文件,所以我们把jdbc.properties名称改为application.properties
3、在JdbcConfiguration类中注入JdbcProperties四种方式
(1) @Autowired注入(常用方式)
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
@Autowired
private JdbcProperties jdbcProperties;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(jdbcProperties.getUrl());
dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
dataSource.setUsername(jdbcProperties.getUsername());
dataSource.setPassword(jdbcProperties.getPassword());
return dataSource;
}
}
(2)构造函数注入
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
private JdbcProperties jdbcProperties;
public JdbcConfiguration(JdbcProperties jdbcProperties){
this.jdbcProperties = jdbcProperties;
}
@Bean
public DataSource dataSource() {
// 略
}
}
(3)@Bean方法的参数注入
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
@Bean
public DataSource dataSource(JdbcProperties jdbcProperties){
DruidDataSource dataSourse = new DruidDataSource();
dataSourse.setDriverClassName(jdbcProperties.getDriverClassName());
dataSourse.setUrl(jdbcProperties.getUrl());
dataSourse.setUsername(jdbcProperties.getUsername());
dataSourse.setPassword(jdbcProperties.getPassword());
return dataSourse;
}
}
(4)
把@ConfigurationProperties(prefix = "jdbc")
声明在需要使用的@Bean
的方法上,然后SpringBoot就会自动调用这个Bean(此处是DataSource)的set方法,然后完成注入。
**使用的前提是:该类必须有对应属性的set方法!
@Configuration
public class JdbcConfiguration {
@Bean
// 声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DataSource中
@ConfigurationProperties(prefix = "jdbc")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
}