Spring Boot 配置绑定
配置绑定就是将配置文件参数和JavaBean中的属性绑定起来,比如:
- 数据库连接信息
- redis配置信息
- rabbitMq中间件信息
Spring Boot 提供两种配置绑定方式:
- 使用@ConfigurationProperties
- 使用@Value
@Value
当我们需要为若干个属性添加配置时,我们可以使用@Value
- 在application.properties添加配置参数
book.name=钢铁是怎么练成的
book.price=100
book.publisher=文艺出版社
- 添加普通类,并添加@Component注解
package com.ibm.cn.config;
import org.springframework.stereotype.Component;
/**
* @author 苏格拉没有底
* @version 1.0
* @DATE 2021/9/10 10:09
*/
@SuppressWarnings("all")
@Component
public class Book {
private String name ;
private Long price ;
private String publisher ;
// getter , setter , toString ...
}
- 在需要绑定的属性上添加@Value注解
@Value("${book.name}")
private String name ;
@Value("${book.price}")
private Long price ;
@Value("${book.publisher}")
private String publisher ;
- 编写测试类
@Autowired
Book book ;
@Test
void testBook(){
System.out.println(book);
}
- 查看结果:
@ConfigurationProperties
当需要绑定的属性较少时, 我们可以使用@Value ; 当需要绑定的属性较多时 , 我们使用@ConfigurationProperties
- 添加配置文件bookConfig.properties
book.name=钢铁是怎么练成的
book.price=100
book.publisher=文艺出版社
- 添加配置类
注意:一定要添加PropertySource注解,并指定配置文件名称以及编码类型, 否则可能会产生中文乱码
package com.ibm.cn.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author 苏格拉没有底
* @version 1.0
* @DATE 2021/9/10 9:23
*/
@SuppressWarnings("all")
@Component
@ConfigurationProperties(prefix="book")
@PropertySource(value = {"classpath:bookConfig.properties"} ,encoding = "utf-8")
public class TestBookConfig {
private String name ;
private Long price ;
private String publisher ;
// getter , setter , toString ...
}
- 编写测试类
@Autowired
TestBookConfig testBookConfig ;
@Test
void testConfig(){
System.out.println(testBookConfig);
}
- 查看结果
- 总结
- 配置类要加上@ConfigurationProperties, 并指定属性prefix为配置文件中的前缀
- 配置类@PropertySource,并指定配置文件名称以及编码类型, 否则可能会产生中文乱码
- 配置类一定要加上@Component, 需要将该配置加载到容器中才能被使用