1.springboot默认会加载application.yml的配置文件,但是自定的配置文件需要自己指定加载路径
如下,自定义abc.yml
usr:
name: 张三
age: 20
like: 阅读
2.编写配置类,添加@PropertySource注解,指定配置文件路径,另外如果配置文件中有层级关系,如usr.name,usr.age时,还需要添加@ConfigurationProperties指定前缀
package com.xxx.xxx;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "classpath:abc.yml", encoding = "utf-8")
@ConfigurationProperties(prefix = "usr")
public class Infos {
@Value("${name}")
private String name;
@Value("${age}")
private int age;
@Value("${like}")
private String like;
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;
}
public String getLike() {
return like;
}
public void setLike(String like) {
this.like = like;
}
@Override
public String toString() {
return "Infos{" +
"name='" + name + '\'' +
", age=" + age +
", like='" + like + '\'' +
'}';
}
}
3.测试类中自动注入:
package com.xxx;
import com.home.entity.Infos;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@SpringBootTest
class SpringbootTestApplicationTests {
@Autowired
private Infos infos;
@Test
void testProperties() {
System.out.println(infos);
}
}
运行结果:
Infos{name='张三', age=20, like='阅读'}