优雅读取yml中的属性
2021-11-09 本文已影响0人
夜色001
我们知道@Value可以读取yml中的属性,但每个地方都要写一遍,显得很笨重。
使用@ConfigurationProperties(prefix=web.api)注解,可以将属性与对象映射起来。并且自动支持yml属性的横线转驼峰格式。
有的地方我们不希望通过@Autowire注解引入配置,我们可以在配置文件中添加static方法,则直接可以通过“类名.方法名”的方式获取配置。但前提是需要修改set方法,让程序在启动时提前给静态成员赋值。
public void setBasePath(String basePath) {
SystemConfig.basePath = basePath;
}
package pro.haichuang.jiudian.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 读取项目相关配置
*
* @author yangkunlin
*/
@Component
@ConfigurationProperties(prefix = "web")
@Data
public class SystemConfig {
/**
* 上传路径
*/
private static String basePath;
public static String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
SystemConfig.basePath = basePath;
}
/**
* 获取下载路径
*/
public static String getDownloadPath() {
return getBasePath() + "/download/";
}
}
#存储的基本路径
web:
upload-base-path: /www/wwwroot/xxxx/upload/
base-path: /www/wwwroot/xxxx/
upload-path: /files/
img-base-path: ${web.upload-base-path}images/
pdf-base-path: ${web.upload-base-path}pdf/
video-base-path: ${web.upload-base-path}files/
log-base-path: ${web.upload-base-path}logs/
img-path: ${web.upload-path}images/
pdf-path: ${web.upload-path}pdf/
video-path: ${web.upload-path}files/
log-path: ${web.upload-path}logs/