我从资源加载json文件时遇到问题。 这是我的代码:
public void setConfiguration() {
try {
ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
Resource[] resources = resolver.getResources("classpath*:/configuration.json");
if (resources.length == 0) {
log.warn("Configuration could not be loaded from file! Using default configuration.");
configuration = getDefaultConfiguration();
}
for (Resource resource: resources){
configuration = new ObjectMapper().readValue(resource.getInputStream(), Configuration.class);
if (configuration != null) {
log.debug("Configuration found (using PathMatchingResourcePatternResolver)");
break;
}
}
} catch (Exception e) {
log.warn("Configuration could not be loaded from file! Using default configuration.", e);
configuration = getDefaultConfiguration();
}
}
始终采用默认配置。有谁知道它为什么不从json文件中获取值?
答案 0 :(得分:0)
您需要使用:
("classpath:"+this.config.getClassPathRoot() + "/**/*"+jsonFileExtension)
获取资源。
我这也无法通过调用默认构造函数来尝试使用该对象:
PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
答案 1 :(得分:0)
try {
Resource resource = new ClassPathResource("classpath:configuration.json");
InputStream resourceInputStream = resource.getInputStream();
if (resourceInputStream == null) {
log.warn("Configuration could not be loaded from file! Using default configuration.");
configuration = getDefaultConfiguration();
}
else {
configuration = new ObjectMapper().readValue(resourceInputStream, Configuration.class);
if (configuration != null) {
log.debug("Configuration found (using PathMatchingResourcePatternResolver)");
break;
}
}
} catch (Exception e) {
log.warn("Configuration could not be loaded from file! Using default configuration.", e);
configuration = getDefaultConfiguration();
}
答案 2 :(得分:0)
如果您的项目是Maven项目,也许您应该在pom中添加一些配置。
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.json</include>
</includes>
</resource>
</resources>