我有一个 springboot 命令行应用程序,其中生产命令行参数之一是绝对基本路径。对于这个例子,我们将其称为
"/var/batch/"
我在 production.yml 文件中设置基本路径,就像这样使用默认值。
公司: 基本路径:${基本路径:/var/default/}
然后我有一个 ApplicationConfig.java 文件,它使用该基本路径来创建一堆文件路径,如下所示。
@ConfigurationProperties(prefix = "company")
public class ApplicationConfig {
private String basePath;
public String getPrimaryCarePath() {
return basePath + "ADAP-2-PCProv.dat";
}
public String getPrimaryCareDetailPath() {
return basePath + "ADAP-2-" + getBatchNo() + ".det";
}
... additional files.
}
最后,文件路径像这样传递到我的 css 解析器中。
public List<T> readCsv() throws IOException {
try (BufferedReader bufferedReader = Files.newBufferedReader(Paths.get(filePath))) {
return new CsvToBeanBuilder(bufferedReader)
.withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS)
.withType(subClass)
.withSeparator('\t')
.withIgnoreLeadingWhiteSpace(true)
.build().parse();
}
}
现在生产中一切正常,但我们在尝试运行突变测试时遇到一些问题。看起来 csv 解析器正在寻找绝对路径而不是相对路径。我们的 application-test.yml 文件中有以下路径。
company:
basePath: src/test/resources/
我们所有的测试文件都存储在测试资源包中,所以我的问题是我们如何使用填充 ApplicationConfig.java 文件的测试资源的相对路径,同时仍然能够使用绝对路径进行生产?我想我可以使用 ClassPathResource 通过测试设置覆盖基本路径,但想知道是否有更好的方法。
最佳答案
您需要两种类型的配置:一种用于资源,一种用于绝对路径。
我建议添加一个新属性app.file.path.type
,其值为resources
和absolute
。您可以定义一个名为 FileProvider
的新接口(interface)。
public interface FilePathProvider(){
Path getFilePath();
}
您可以使用@ConditionalOnProperty
定义2个不同的bean并设置文件路径策略:
@Configuration
public class ApplicationConfig{
@Bean
@ConditionalOnProperty(
name = "app.file.path.type",
havingValue = "absolute")
public FilePathProvider absoluteFilePathProvider(ApplicationConfig applicationConfig){
return () -> Paths.get(applicationConfig.getBasePath());
}
@ConditionalOnProperty(
name = "app.file.path.type",
havingValue = "resources")
@Bean
public FilePathProvider resourceFilePathProvider(ApplicationConfig applicationConfig){
return () -> Paths.get(this.getClass().getClassLoader().getResource(applicationConfig.getBasePath()).getPath());
}
}
在开发和测试模式下,您将拥有 app.file.path.type=resources
,在生产模式下,您将拥有 app.file.path.type=absolute
。
这种方法的优点是您也可以在开发中将该属性设置为absolute
。
关于java - 从资源目录获取文件进行单元测试,但获取产品的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53047813/