2017-05-27 83 views
0

在弹簧基础项目中,我们要从classpath加载文件,必须从spring el表达式评估文件位置。使用弹簧加载文本文件,其位置定义为弹簧el

此功能目前在春季加载属性文件,位置可以是任何Spring EL

<util:properties id="samplePolicy" 
    location="classpath:/conf/#{environment.getActiveProfiles()[1]} 
       /sample.properties" /> 

这正是我们想要的,但不是加载属性文件,只是一个文本文件。

所以我们尝试如下:

我们使用ResourceLoader

@Autowired 
private ResourceLoader resourceLoader; 
//And then .... 
resourceLoader.getResource("classpath:myfile.txt"); 

如何过resourceLoader.getResource("classpath:/conf/#{environment.getActiveProfiles()[1]}}/sample.txt")不起作用。

看来,resourceLoader.getResource不解析春季EL。

虽然我们可以解析EL然后从资源加载器中获取文件,但我们不知道它是否可以做得更容易,可能是一些内置函数。

回答

2

看来resourceLoader.getResource不能解析Spring EL。

资源加载器不分析SpEL,应用程序上下文在加载时会执行。

注入值转换成字符串场...

@Value("classpath:/conf/#{environment.getActiveProfiles()[1]}/sample.txt") 
private String location; 

resourceLoader.getResource(this.location);