方法一
1、application.properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///xxx
jdbc.username=root
jdbc.password=root
2、创建实体类
并生成 getter 和 setter 方法
public class JdbcProperties {
private String driverClassName;
private String url;
private String username;
private String password;
}
3、创建配置类
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)//指定加载哪个配置属性类
public class JdbcConfiguration {
@Bean
public DataSource getDataSource(JdbcProperties jdbcProperties){
DruidDataSource source = new DruidDataSource();
source.setDriverClassName(jdbcProperties.getDriverClassName());
source.setUrl(jdbcProperties.getUrl());
source.setUsername(jdbcProperties.getUsername());
source.setPassword(jdbcProperties.getPassword());
return source;
}
}
方法二
只需要配置类编写,不需要实体类
1、application.properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///xxx
jdbc.username=root
jdbc.password=root
2、创建配置类
@Configuration
public class JdbcConfiguration {
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource getDataSource(){
DruidDataSource source = new DruidDataSource();
return source;
}
}