Reputation: 1324
Hi I want to use @PropertySource in spring for a custom resource ie say xyz://path/x.txt instead of standard protocols like classpath file and so on which it already supports .I have found a way to do the same in spring Boot that is by SpringApplication as below with a custom ResourceLoader
protected WebApplicationContext run(SpringApplication app){
app.setResourceLoader(new MyCustomResourceLoader);
return (WebApplicationContext )app.run();
}
The same works well and now I can define propertySource like @PropertySource("xyz://path/y.txt") .But I was not able to figure out how to override/customize the same in a normal spring application .Though of trying ways by using ResourceLoaderAware and BeanPostProcessor but couldnt figure it out.
Any help ..
UPDATE Stuff I will do in my custom ResourceLoader
public Class CustomResourceLoader extends DefaultResourceLoader{
@Override
public Resource getResource(String location){
if(location.startsWith("xyz://"){
return new XYZResource(new URI(location));
}
return super.getResource(location);
}
Now I just need a way to tell spring to use this instead of the defaultresourceloader it's possible as I mentioned in SPring boot but need to figure out how to do it in pure Spring.
Upvotes: 0
Views: 1816
Reputation: 1324
Thanks to @chris-beams, who gave a workaround. Summarizing, the following changes required:
Extend AnnotationConfigWebApplicationContext and override its getResource method by using your custom resourceloader as below
@Override
public Resource getResource(String location)
{
ResourceLoader loader = SingletongINSTANCE.getCustomResourceLoader();
return loader.getResource(location);
}
This can be done with either by using the custom AnnotationConfigWebApplicationContext entry in web.xml or via WebApplicationInitializer .
Also for more convenient support for custom resource loaders raised https://jira.spring.io/browse/SPR-13905
Upvotes: 0
Reputation: 1483
Take a look at ConfigurableEnvironment
, where you'll find first-class support for registering and ordering custom PropertySource
instances:
Upvotes: 1