springboot系列-获取配置文件值的模型设计,在项目中灵活统一配置配置文件的各项值,统一配置、统一管理。
设计的需求
在做报表模块dy-u-report时,需要读取配置文件中字体路径、模板路径、生成路径等配置信息,直接读取繁琐不直观,如果配置信息修改,维护困难,所以通过配置类映射配置信息,读取数据时直接调用配置类的属性即可,维护修改时只维护相应的配置类即可。
代码实现
配置文件
1 2 3
| report.pdf.path.font = /etc/config/dy-web/pdf/font/ report.pdf.path.template = /app/template/ report.pdf.path.genDir = /etc/config/dy-web/pdf/
|
配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
@ConfigurationProperties(prefix = "report.pdf.path") public class ReportProperties {
private String font;
private String template;
private String genDir;
public String getFont() { return font; }
public void setFont(String font) { this.font = font; }
public String getTemplate() { return template; }
public void setTemplate(String template) { this.template = template; }
public String getGenDir() { return genDir; }
public void setGenDir(String genDir) { this.genDir = genDir; } }
|
配置类注册bean
1 2 3 4 5 6 7 8 9
|
@Configuration @EnableConfigurationProperties(ReportProperties.class) public class ReportConfig { }
|
调用配置类
非静态方法引用
1 2 3 4 5
| @Autowired private ReportProperties reportProperties;
String genDir =reportProperties.getGenDir();
|
静态方法应用
在工具类中静态方法应用时,要将工具类注入成bean交给spring管理,获取配置类要在setter方法上面加上@Autowired
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
@Component public class ReportUtil { private ReportUtil(){}
private static final String FILE_SEPERATOR = "/";
private static ReportProperties reportProperties;
@Autowired public void setReportProperties(ReportProperties reportProperties) { ReportUtil.reportProperties = reportProperties; }
public static List<String> getFontPathList() {
return FileUtil.getAllFileNames(reportProperties.getFont()); } }
|