Spring: @PropertySource注解如何能够引入非classpath下的资源文件?

网上的资料一般在使用@PropertySource的时候,都喜欢用@PropertySource("classpath:/document.properties")
这种形式

现在我把资源文件的路径放在application.properties里

config.path=/home/myservice/config.properties

然后在java源码里:

@PropertySource(value = {"${config.path}"}, encoding="utf-8")
public class MyConfig {
    @Value("${myconfig.index}")
    private String index;

    public String getIndex() {
       return index;
    }

}

但是出错:

Caused by: java.io.FileNotFoundException: class path resource [home/myservice/config.properties] cannot be opened because it does not exist

阅读 12.8k
3 个回答

你是直接读取绝对路径的磁盘文件,需要加上 file:${config:path}

配置的路径要相对于class文件的根目录,class path

使用:@PropertySource(value = "file:${config.path}",ignoreResourceNotFound = true)
不要忘记@Configuration注解

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题