Faraj Farook
Faraj Farook

Reputation: 14855

Adding external static files (css, js, png ...) in spring boot

Background


I have a spring boot application which has the logo.png file added to the static folder of the resource file, which is eventually built into the jar file which is used in the execution.

This jar application need to be run in multiple instances for different clients. So what I did is create an external application.properties file which distinguish the settings for each users. http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Problem


But the problem is, i need to change the logo of each instance of my application. I cannot embed the customer logos into my application jar. Rather I need to keep it external like my application.properties.

For the moment, what I have done is check for the file logo.png in the same folder of jar of execution, and if excist, read the file, get base64 data and show it in the img tag.

But I want this to be done in a proper way as static content. I need the static content to be externalized. so I can let each customer have a specific instance of the jar running with different static resource content

For example. I need to keep the external static files as below and access from the urls in my view href or src attributes of the html tags.

Summary


Required folder structure

+ runtime
  - myapp-0.1.0.jar
  - application.properties
  + static
    - logo.png

Should be able to access

<img th:src="@{/logo.png}" />

Upvotes: 5

Views: 6259

Answers (2)

dirbacke
dirbacke

Reputation: 3021

The WebMvcConfigurerAdapter is deprecated. As from Spring Boot 2.x you could use WebMvcConfigurer instead.

@Configuration
public class MediaPathConfig {
    // I assign filePath and pathPatterns using @Value annotation
    private String filePath = "/ext/**"; 
    private String pathPatterns = "/your/static/path/";

    @Bean
    public WebMvcConfigurer webMvcConfigurerAdapter() {
        return new WebMvcConfigurer() {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                if (!registry.hasMappingForPattern(pathPatterns)) {
                    registry.addResourceHandler(pathPatterns)
                            .addResourceLocations("file:" + filePath);
                }
            }
        };
    }
}

Upvotes: 0

sodik
sodik

Reputation: 4683

You can use resource handlers to serve external files - e.g.

@Component
class WebConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/ext/**").addResourceLocations("file:///yourPath/static/");
    }

}

Upvotes: 5

Related Questions