文章目录
一、直接赋值
配置文件application.properties:
#随机值属性
my.number.a=${random.value}
my.number.b=${random.int}
my.number.c=${random.int(1,100)}
my.number.uid=${random.uuid}
my.number.myfriend=${myobject.name}
读取配置:
@Component
@Data
@ToString
public class MyNumber {
@Value("${my.number.a}")
private String a;
@Value("${my.number.b}")
private int b;
@Value("${my.number.c}")
private int c;
@Value("${my.number.uid}")
private String uid;
@Value("${my.number.myfriend}")
private String myfriend;
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Dur5Course2SpringbootApplication.class)
class Dur5Course2SpringbootApplicationTests {
@Autowired
private MyNumber myNumber;
@Test
void myObject(){
System.out.println(myNumber);
}
结果:
二、通过 PropertySource注解读取自定义配置文件
stu.properties:
#配置学生对象的初始化信息
student.sid=2
student.sname=张三
student.score=99.5f
读取配置:
@Component
@Data
@ToString
@PropertySource(value = "classpath:stu.properties",encoding = "utf-8") //创建该bean的时候读取配置文件
public class Student {
@Value("${student.sid}")
private int sid;
@Value("${student.sname}")
private String sname;
@Value("${student.score}")
private float score;
}
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Dur5Course2SpringbootApplication.class)
class Dur5Course2SpringbootApplicationTests {
@Autowired
private Student student;
@Test
public void test(){
System.out.println(student);
}
结果:
三、在spring工厂启动之前,通过全局环境变量env预先加载配置:通过运行自定义的EnvirionmentProcessor类。(加载时间在springboot加载之前)
在resource下面建一个META-INF目录:
在该目录下建立一个spring.factories文件:
org.springframework.boot.env.EnvironmentPostProcessor=com.wance.processor.MyEnvironmentPostProcessor
在processor目录下建立一个MyEnvironmentPostProcessor类:
/**
自定义环境处理,在运行SpringApplication之前加载任意配置文件到Environment环境中
*/
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
//Properties对象
private final Properties properties = new Properties();
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,SpringApplication application) {
System.out.println("通过processor加载自定义配置");
//自定义配置文件
String[] profiles = {
"stu.properties"
};
//循环添加
for (String profile : profiles) {
//从classpath路径下面查找文件
Resource resource = new ClassPathResource(profile);
//加载成PropertySource对象,并添加到Environment环境中
environment.getPropertySources().addLast(loadProfiles(resource));
}
}
//加载单个配置文件
private PropertySource<?> loadProfiles(Resource resource) {
if (!resource.exists()) {
throw new IllegalArgumentException("资源" + resource + "不存在");
}
try {
//从输入流中加载一个Properties对象
properties.load(new InputStreamReader(resource.getInputStream(),"utf-8"));
return new PropertiesPropertySource(resource.getFilename(), properties);
}catch (IOException ex) {
throw new IllegalStateException("加载配置文件失败" + resource, ex);
}
}
}
实体类:
@Component
@Data
@ToString
public class Student {
@Value("${student.sid}")
private int sid;
@Value("${student.sname}")
private String sname;
@Value("${student.score}")
private float score;
}
测试: