自 Spring Boot 2.x 以来,我在配置属性功能上遇到了意外行为。在 1.5.x 上,它工作得很好。
状况Resource[]
定义自定义配置属性类的属性- 使用前缀指定属性值
classpath*:
,例如classpath*:files/*.txt
- 绑定
Resource
与模式字符串匹配的多个实例
- 绑定一个包含指定模式字符串的单个
Resource
,例如classpath*:files/*.txt
package com.example.demoresources;
import org.assertj.core.api.Assertions;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "my.files=classpath*:files/*.txt")
@EnableConfigurationProperties({DemoResourcesApplicationTests.MyProperties.class})
public class DemoResourcesApplicationTests {
@Autowired
MyProperties myProperties;
@BeforeClass
public static void setup() throws IOException {
Path dir = Paths.get("target", "test-classes", "files");
Files.createDirectories(dir);
createFileIfNotExist(dir.resolve("a.txt"));
createFileIfNotExist(dir.resolve("b.txt"));
}
private static void createFileIfNotExist(Path path) throws IOException {
if (!path.toFile().exists()) {
Files.createFile(path);
}
}
@Test
public void contextLoads() {
Resource[] files = myProperties.getFiles();
List<String> fileNames = Arrays.stream(files).map(Resource::getFilename).collect(Collectors.toList());
Assertions.assertThat(fileNames)
.hasSize(2)
.contains("a.txt", "b.txt"); // Success with Spring Boot 1.5.x but fail with Spring Boot 2.x ...
}
@ConfigurationProperties(prefix = "my")
public static class MyProperties {
private Resource[] files = {};
public void setFiles(Resource[] files) {
this.files = files;
}
public Resource[] getFiles() {
return files;
}
}
}