我有一个包含许多.properties文件的项目,这些属性文件的数量变化很大。我不想用以下内容导入每个单独的属性:
@PropertySource(value = "classpath:some.properties")
所以我尝试使用以下简化的示例代码从目录中加载所有属性:
@Configuration
@Import(SomeClass.class)
public class SimpleConfiguration {
private static final String TABLE_DIR = "src/main/resources/tables";
private static final String TABLE_RESOURCE = "/tables/";
@Autowired
public SomeClass someClass;
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
Path dir = Paths.get(TABLE_DIR);
List<ClassPathResource> allProperties = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file : stream) {
allProperties.add(new ClassPathResource(TABLE_RESOURCE + file.getFileName()));
}
} catch (IOException | DirectoryIteratorException x) {
System.err.println(x);
}
ClassPathResource[] props = allProperties.toArray(new ClassPathResource[allProperties.size()]);
Resource[] resources = props;
properties.setLocations(resources);
properties.setIgnoreUnresolvablePlaceholders(true);
return properties;
}
}
简化示例类
public class SomeClass {
@Autowired
private Environment env;
@PostConstruct
public void doSomething() {
String tableName = "person";
String someValue = env.getProperty(tableName + ".primaryKey");
}
}
尝试获取值时,env.getProperty
会引发Caused by: java.lang.NullPointerException: null
,因为Environment
对象不包含我预先加载PropertySourcesPlaceholderConfigurer
如何在配置PropertySourcesPlaceholderConfigurer
后检索属性,是否仍可以使用自动装配的Environment
对象进行检索?