Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load xml resource file using wild card in Spring 3.1

I want to load xml files which contains some error definitions of several modules in a Spring Maven project. I want to load and then pass the file to a JAXB unmasheller.

This is what I have done so far

String path = "classpath*:/**/definitions/error-definition.xml";
ClassPathResource resource = new ClassPathResource(path);
unmarshaller.unmarshall(resource);

My resource files are located as follows

src/main/resource/module1/definitions/error-definition.xml

src/main/resource/module2/definitions/error-definition.xml

This gives me the following error

java.io.FileNotFoundException: class path resource [classpath*:/**/definitions/error-definition.xml] cannot be resolved to URL because it does not exist

but when I change the path as follows

 String path = "/module1/definitions/error-definition.xml";

It works

Following are the other wild card which I tried with no luck

String paths = "classpath:/**/definitions/error-definition.xml";
String paths = "classpath*:error-definition.xml";
String paths = "classpath*:*.xml";

What I want to do is to use wild card to get the xml files from any folder under src/main/resource

I referred several previous SO answers but still couldn't figure out what Im doing wrong.

like image 1000
virtualpathum Avatar asked Dec 25 '22 10:12

virtualpathum


1 Answers

To load resource inject the ResourceLoader into your class. You can do this by either implementing ResourceLoaderAware or simply annotate a field of type ResourceLoader with @Autowired.

public class YourClass {

    @Autowired
    private ResourceLoader rl;

}

Now that you have the ResourceLoader you can use the ResourcePatternUtils to actually load the resources.

public Resource[] loadResources() {
    return ResourcePatternUtils.getResourcePatternResolver(rl).getResources("classpath:/directory/**/*-context.xml);

}
like image 199
M. Deinum Avatar answered Jan 18 '23 22:01

M. Deinum