SpringBoot(二)自定义配置
SpringBoot 自定义配置项
SpringBoot 提供三种方式自定义配置项:
1 2 3
| - 1、@Value - 2、@ConfigurationProperties - 3、@Environment
|
@Value注解
在 application.properties 配置文件中添加自定义配置项:
1 2
| com.hqd8080.costum.firstname=han com.hqd8080.costum.secondname=quanding
|
使用 @Value 读取配置项
1 2 3 4 5
| @Value("${com.hqd8080.costum.firstname}") private String firstName;
@Value("${com.hqd8080.costum.secondname}") private String secondName;
|
1
| 注意 @Value 默认读取的是 application.properties 配置文件中的配置项,如果是其他配置文件要使用:@PropertySource 注解指定对应的配置文件;
|
@Environment注解
1 2 3 4 5 6 7 8 9 10 11
| @Autowired private Environment env;
@Test void getEnv() { System.out.println(env.getProperty("com.hqd8080.costum.firstname")) System.out.println(env.getProperty("com.hqd8080.costum.secondname")) }
#使用 Environment 无需指定配置文件,获取到的是系统加载到的全部配置项; #需要注意配置文件的编码格式
|
@ConfigurationProperties 注解
1 2 3
| - 1、创建自定义配置文件 - 2、创建实体类 - 3、调用配置项
|
1、创建自定义配置文件
1 2 3 4 5
| website.properties 配置文件中:
com.hqd8080.resource.name=mall com.hqd8080.resource.website=www.mall.com com.hqd8080.resource.language=java
|
2、创建实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @Configuration @ConfigurationProperties(prefix = "com.hqd8080.resource") @PropertySource(value = "classpath:website.properties") public class WebSiteProperties { private String name; private String website; private String language;
public String getName() { return name; } public void setName(String name) { this.name = name; } }
1、@Configuration 定义此类为配置类,用于构建 bean 定义并初始化到 Spring 容器; 2、@ConfigurationProperties(prefix = "com.hqd8080.resource") 绑定配置项,其中 prefix 表示所绑定的配置项名的前缀; 3、@PropertySource(value = "classpath:website.properties") 指定读取的配置文件及其路径;@PropertySource 不支持引入 YML 文件;
通过上面的 WebSiteProperties 类即可读取全部对应的配置项;
|
3、调用配置项
1 2 3 4 5 6 7 8 9
| @Autowired private WebSiteProperties website;
@Test void getProperties() { System.out.println(website.getName()) System.out.println(website.getWebsite()) System.out.println(website.getLanguage()) }
|
小结
使用配置文件注意事项:
1 2 3 4 5 6 7 8 9 10
| - 1、使用 YML 配置文件时注意空格和格式缩进的问题; - 2、properties 配置文件默认使用的是 ISO8859-1 编码格式,容易出现乱码问题; 如果含有中文,加入 spring.http.encoding.charset=UTF-8 配置即可;
- 3、properties 配置的优先级高于 YML文件;因为 YML文件的加载顺序先于 properties 文件; 如果两个文件存在相同的配置;后面加载的 properties 中的配置会覆盖前面 YML 中的配置;
- 4、@PropertySource 注解默认只会加载 properties 文件,YML 不能使用此注解; - 5、简单的配置推荐使用 @Value 复杂对象推荐使用 @ConfigurationProperties; - 6、只有 Spring 容器中的组件才能使用容器提供的各类方法,所以,配置读取类需要增加 @Component 注解才能加入 Sping 容器中;
|