Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pavankjadda/8d17d697f86c1b80cc06c39cec74c87e to your computer and use it in GitHub Desktop.
Save pavankjadda/8d17d697f86c1b80cc06c39cec74c87e to your computer and use it in GitHub Desktop.
Serve Custom static resource locations in Spring Boot

Configure Spring Boot Application to serve Custom Static Resource locations

Static resources can be configured using two approaches in Spring Boot

  • Add custom path in application.properties/application.yaml
  • Implement WebMvcConfigurer addResourceHandlers() method

First configure your SpringSecurity class to accept requests to this resources

@Override
public void configure(WebSecurity web)
{
    web.ignoring()
            .antMatchers( "/static/**","/resources/**", "/js/**", "/css/**", "/images/**");

}

Then use any one of the following way to serve static content

Approach-1

  1. Open application.properties/application.yaml file and add the following line based on your directory structure
spring.resources.static-locations=classpath:/static/,classpath:/static/vendor/,classpath:/static/custom/
  1. By default classpath points to /resources/ directory under project root. So, static folder/file locations should be relative from that directory.

  2. Example:

Absoulte Path: /Users/johnd/IdeaProjects/SpringSessionTest/src/main/resources/static/vendor/css/bootstrap.min.css
Project Structure: SpringSessionTest/src/main/resources/static/vendor/css/bootstrap.min.css

In this case, your static-locations should be spring.resources.static-locations=classpath:/static/,classpath:/static/vendor/ and in your web page you can use
<link href="css/bootstrap.min.css" rel="stylesheet"> to link this stylesheet

Approach-2

  1. Create class ApplicationConfig that extends WebMvcConfigurer interface and configure your locations in CLASSPATH_RESOURCE_LOCATIONS string array
@Configuration
public class ApplicationConfig implements WebMvcConfigurer
{
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
    {
        "classpath:/META-INF/resources/", "classpath:/resources/",
        "classpath:/static/", "classpath:/public/","classpath:/static/vendor/","classpath:/static/custom/"
    };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    }
}
@Sanjay007
Copy link

Here is a resource that talks about handling spring boot static content in variety of ways . I found 4th one interesting
https://www.frugalisminds.com/spring-boot-serve-static-web-content/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment