https://blog.youkuaiyun.com/ityqing/article/details/80541419 这篇文章讲了自定义属性配置,本篇文件告诉你应该怎么写一个自定义配置文件
其实和自定义属性配置差不多,自定义配置是在spring boot已有的配置文件中添加自定义属性, 而自定义配置文件是自己创建配置文件.
定义一个名为 my.properties 的资源文件,自定义配置文件的命名不强制 application 开头
my.age=22
my.name=Levin
其次定义 MyProperties.java 文件,用来映射我们在 my.properties中的内容。
package com.battcn.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:my.properties")
@ConfigurationProperties(prefix = "my")
public class MyProperties2 {
private int age;
private String name;
// 省略 get set
@Override
public String toString() {
return "MyProperties{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
接下来在 PropertiesController 用来注入 MyProperties2 测试我们编写的代码
@GetMapping("/my")
public MyProperties myProperties() {
log.info("=================================================================================================");
log.info(myProperties.toString());
log.info("=================================================================================================");
return myProperties;
}
本文介绍了如何在SpringBoot项目中使用自定义配置文件。通过创建一个名为my.properties的资源文件,并定义对应的MyProperties2 Java类,可以实现对自定义配置的读取。最后,在PropertiesController中注入MyProperties2进行测试。
2705

被折叠的 条评论
为什么被折叠?



