0

In an spring base project, we want to load a file from classpath the file location must be evaluated from an spring el expression.

This feature is currently in spring which loads property files, the location can be any Spring EL.

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

This is exactly what we want but not to load a property file, just a text file.

So we try below:

We use ResourceLoader

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

How ever resourceLoader.getResource("classpath:/conf/#{environment.getActiveProfiles()[1]}}/sample.txt") does not work.

It seems that the resourceLoader.getResource does not parse the Spring EL.

Although we can parse the EL and then get the file from resource loader, we wonder if it can be done easier, may be with some built in function.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173

1 Answers1

2

It seems that the resourceLoader.getResource does not parse the Spring EL.

The resource loader doesn't parse the SpEL, the application context does while it is being loaded.

Inject the value into a String field...

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

and

resourceLoader.getResource(this.location);
Gary Russell
  • 166,535
  • 14
  • 146
  • 179