lusiqi

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
/**
* @description 报表配置文件字段配置映射类
* @author dxy
* @date 2020-01-04
*/
@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
/**
* @description 报表模块配置类
* @author dxy
* @date 2020-01-04
*/
@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
/**
* @Description 报表处理工具类
* @author dxy
* @date 2019-12-04
*/
@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;
}

/**
* 获取pdf支持的所有的中英文字体路径
*
* @return pdf支持的所有的中英文字体路径
*/
public static List<String> getFontPathList() {

// 中文字体: 宋体 、黑体、 楷体 、隶书 、幼圆
// 英文字体: Tohama/Arial/Times New Roman/
return FileUtil.getAllFileNames(reportProperties.getFont());
}
}

 评论