准备工作
-
properties文件
-
映射properties文件的配置类
-
使用到的关键注解
- @Component //将bean交给spring管理
- @ConfigurationProperties(prefix = “前缀”) //除了前缀属性外,还可以添加其它属性,有想法的同学可以查看源码。
作用:将该类与外部配置文件绑定起来,就是与properties文件绑定起来
- @PropertySource(“classpath:config.properties”) // 指定外部配置文件的路径
应用示例
properties文件
config.name=liql
config.age=10
映射properties文件的配置类
配置类需要getter setter方法,且不需要与properties保持完全一致
注意注解的使用
package com.li;
/**
* @author liql
* @date 2021/6/29
*/
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "config") //properties 文件中的前缀为config
@PropertySource("classpath:config.properties") //properties 文件路径
public class TestProperties {
String name;
int age;
String color;//多出来的一个属性
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试
代码
package com.li;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TestpropertiesApplicationTests {
@Autowired
TestProperties testProperties;
@Test
void contextLoads() {
System.out.println("age="+testProperties.age);
System.out.println("name="+testProperties.name);
//由于color属性在properties文件中没有注明,所以映射结果为空。
System.out.println("color="+testProperties.color+" 由于color属性在properties文件中没有注明,所以映射结果为空");
}
}
测试结果
在这里插入图片描述