A:

  1. Step one

Define properties in resources

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=admin
Copy the code
  1. Write a JdbcProperties class and configure the ConfigurationProperties annotation. Use lombok to configure the Data annotation. Getters and setters are generated automatically at compile time
package com.jserm.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "jdbc")
@Data
public class JdbcProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}
Copy the code
  1. Writing a JdbcConfig class and configuration properties into the DataSource, you must configure @ EnableConfigurationProperties annotations (JdbcProperties. Class)
package com.jserm.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfig { @Bean public DataSource dataSource(JdbcProperties properties) { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(properties.getDriverClassName()); dataSource.setUrl(properties.getUrl()); dataSource.setUsername(properties.getUsername()); dataSource.setPassword(properties.getPassword()); return dataSource; }}Copy the code

Way 2

  1. Step one

Define properties in resources

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=admin
Copy the code
  1. Write a JdbcConfig class that writes the ConfigurationProperties annotation directly to the dataSource method instead of to the JdbcProperties class configuration in another class file, and dispenses with getters and setters
package com.jserm.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class JdbcConfig { @Bean @ConfigurationProperties(prefix = "jdbc") public DataSource dataSource() { return new DruidDataSource(); }}Copy the code

Methods three

  1. Write a.yml file instead of a.properties file. Write a.yml file instead of a.properties file
jdbc:
  driverClassName: com.mysql.cj.jdbc.Driver
  url: jdbc:mysql://localhost:3306/ssm
  username: root
  password: admin
Copy the code