Serve static resources within jar files by Spring boot
Asked Answered
U

1

6

I'm developing a solution by multiple maven modules to handle different bounded contexts.

Thanks to spring boot each module exposes own rest api and all of them hosted in one maven module with a class that annotated by @SpringBootApplication. The simplified project structure is looks like this:

parent  
|-- pom.xml  
|-- ...
|-- host   
  |-- Application.java      
  |-- resources
     |-- index.html
|-- driver
  |-- api     
  |-- resources
     |-- register.html
|-- notify
  |-- ...
|-- passenger
  |-- ...

I've tried to use the same pattern when facing with the composite UI: one place that keeps layouts, static resources and in the meantime, the html pages belong to each bounded context that kept in it's maven module.

The problem is as I've found in the spring boot doc there is no way to serves static resources from the other jar files.

Is there any solution to get this functionality or is there any architectural mistake here? or something outside of the spring (e.g. overlay) is the solution?

Unicef answered 1/7, 2016 at 21:41 Comment(5)
If you put the static files in the path "src/main/resources/static", they should be packaged in the folder "static" in the JAR file, which then should be served as static resources. If you have any problems with that, specify your errors.Tadio
Do you mean put the all static files under the 'host' module likes index.html? they are already in the right path and served by spring. But what about register.html that is in the another maven module and packaged as a seperate JAR file.Unicef
if the file "register.html" is in the folder "static" in the JAR, it will be recognized and served by Spring as static resource. If it doesn't work, then you might post more information about your configuration and logfiles.Tadio
Thank you very much for taking the time to answer. You right, I finally found the mistake that caused the static resource not loaded.Unicef
...aand? what was the mistake?Induna
D
8

extends WebMvcConfigurerAdapter and override addResourceHandlers

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/");
}

refer spring-boot-app-does-not-serve-static-resources-after-packaging-into-jar

Diamond answered 12/7, 2017 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.