Spring Resource Download

Can someone explain how Spring decides where to look for resources when you use the ResourceLoader.getResource (...) method?

I have a problem with a multi-module maven application created using Spring Boot, as a result of which, in my integration tests, my code can find resources using resourceLoader.getResource("templates/") or even resourceLoader.getResource("classpath:templates/") . So far so good ...

However, when the module is eventually packaged into an executable JAR and launched with the built-in Tomcat, resources can no longer be resolved. I also tried resourceLoader.getResource("classpath*:templates/") without success.

What I find is that when I add the registration operator to display the URL used in the search, I get the path to one of the other project modules (and not the one that actually contains this resource). For example: jar:file:/Users/david/exmaple/target/spring-boot-0.0.1-SNAPSHOT.jar!/lib/module1-0.0.1-SNAPSHOT.jar!/templates/ , whereas I believe that the resource is in jar:file:/Users/david/exmaple/target/spring-boot-0.0.1-SNAPSHOT.jar!/lib/module2-0.0.1-SNAPSHOT.jar!/templates/

The resource loader was obtained from the Autwired constructor parameter.

Thanks in advance for any tips.

Edit

Just in case, this is unclear or important, my integration tests for the module in question do not know about another module. I have modules module1, module2 and spring-boot, which have dependencies on modules 1 and module2. Essentially, when I run integration tests for module 2, classpath does not know module 1, so I suspect this has something to do with why it works in tests.

+5
source share
1 answer

When you use the classpath: or classpath*: prefix, internally this happens, essentially by calling ClassLoader.getResources (...) in spring.

The path of the wildcard classes depends on the getResources () method of the base class loader. Since most application servers currently ship their own implementation of the class loader, the behavior may be different, especially when working with jar files. A simple test to check if classpath * is working is to use the classloader to load the file from the jar in the classpath: getClass().getClassLoader().getResources("<someFileInsideTheJar>") . Try this test with files with the same name but placed in two different places. If you return an inappropriate result, check the application server documentation for parameters that might affect the behavior of the class loader.

Do not use the classpath: form as you have several places for the templates/ classloader.

Refer to: resources-classpath-wildcards

+2
source

Source: https://habr.com/ru/post/1211436/


All Articles