Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve static resources within jar files by Spring boot

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?

like image 725
nsafari Avatar asked Jul 01 '16 21:07

nsafari


People also ask

How do spring boots use static resources?

Using Spring BootSpring Boot comes with a pre-configured implementation of ResourceHttpRequestHandler to facilitate serving static resources. By default, this handler serves static content from any of the /static, /public, /resources, and /META-INF/resources directories that are on the classpath.

Where do static files go in Spring Boot?

The file is located in the src/main/resources/static directory, which is a default directory where Spring looks for static content. In the link tag we refer to the main. css static resource, which is located in the src/main/resources/static/css directory. In the main.

How do I run a jar file in Spring Boot?

The Spring Boot Maven Pluginimplement a custom ClassLoader to locate and load all the external jar libraries now nested inside the package. automatically find the main() method and configure it in the manifest, so we don't have to specify the main class in our java -jar command.

How do I add resources to Spring Boot?

The spring-boot:run can add src/main/resources directly to the classpath (for hot reloading purposes) if you enable the addResources flag. This circumvents the resource filtering and this feature. You can use the exec:java goal instead or customize the plugin's configuration, see the plugin usage page for more details.


1 Answers

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

like image 112
赵开元 Avatar answered Oct 02 '22 12:10

赵开元