目标:能够使用@ConfigurationProperties实现Spring Boot配置文件配置项读取和应用
将配置文件中的配项读取到一个对象中;
可以使用Spring Boot提供的注解@ConfigurationProperties ,该注解可以将Spring Boot的配置文件(默认
必须为application.properties或application.yml )中的配项读取到-个对象中。
@ConfigurationProperties(prefix = "jdbc") public class JdbcProperties { private String url; private String driverClassName; private String username; private String password; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } 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; } }
jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3307/test jdbc.username=root jdbc.password=123456
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfig { @Bean public DataSource dataSource(JdbcProperties jdbcProperties){ DruidDataSource dataSource= new DruidDataSource(); dataSource.setDriverClassName(jdbcProperties.getDriverClassName()); dataSource.setUsername(jdbcProperties.getUsername()); dataSource.setPassword(jdbcProperties.getPassword()); dataSource.setUrl(jdbcProperties.getUrl()); return dataSource; }
package test.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.sql.DataSource; @RestController public class HelloController { @Autowired private DataSource dataSource; @GetMapping("hello") public String hello(){ System.out.println("DataSource="+dataSource); return "hello,spring boot!"; } }
启动springboot,断点查看结果
//@ConfigurationProperties(prefix = "jdbc") public class JdbcProperties { private String url; private String driverClassName; private String username; private String password; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } 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; } }
jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3307/test jdbc.usename=root jdbc.password=123456
@Configuration public class JdbcConfig { @ConfigurationProperties(prefix = "jdbc") @Bean public DataSource dataSource() { return new DruidDataSource(); } }
启动springboot,断点查看结果
小结:
●使用@ConfigurationProperties编写配置项类将配置文件中的配置项设置到对象中
●使用@ConfigurationProperties在方法 上面使用