1. 前言
我们在实际开发过程中,如果有一个写在代码中的路径需要修改这时就需要开发人员修改源码然后编译再替换,当项目处于生产环境时,开发人员是不会维护的,有专门的维护人员,如果路径写在配置文件中,只需维护人员更改配置重启,提高程序的健壮性。
2. 具体实现
- 在项目中的resources文件夹中创建配置文件
- 引入外部配置文件默认是properties文件,如需要支持yaml/或yml时需要引入工具类
package com.chuan.ping.backend.util;
import java.io.IOException;
import java.util.Properties;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
/**
* @Describe: 引入外部配置文件(默认是properties文件,此处设置成也支持yaml/yml文件)
* @User: CS
* @CreateTime: 2021-07-20 11:19
**/
public class YamlPropertySourceFactoryUtil extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = (name == null) ? resource.getResource().getFilename() : name;
assert sourceName != null;
String sourceName1 = ".yml";
String sourceName2 = ".yaml";
if (sourceName.endsWith(sourceName1) || sourceName.endsWith(sourceName2)) {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
Properties properties = factory.getObject();
assert properties != null;
return new PropertiesPropertySource(sourceName, properties);
}
return super.createPropertySource(name, resource);
}
}
- 在实体类中实现Serializable
@ConfigurationProperties(prefix = "common.path")
@PropertySource(value = "classpath:common-path.yml", factory = YamlPropertySourceFactoryUtil.class)
@Component
@Data
public class FilePath implements Serializable {
private String radar;
private String gridPoint;
}
@ConfigurationProperties 定义配置文件里的前缀
@PropertySource 设置支持配置文件为yml/yaml格式
- 使用时将实体类注入进来
private final FilePath path;
public RadarController(FilePath path) {
this.path = path;
}