Spring Boot unabe to serve static image from resource folder

@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {

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

I hope this helps you!

Maybe you have added @EnableWebMvc which looks for handlers corresponding to /api/images/social/facebook/f_logo.jpg. Just remove that & provide WebMvcConfigurer or WebMvcConfigurationSupport similar to what I have posted.


Same problem with me. (Spring Boot 2)

I resolve below.

Step 1: Move images folder from src/main/resources/static/images to src/main/webapp/WEB-INF/images

Step 2: Look up SpringBootMainApplication.java add code

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

    // Register resource handler for images
    registry.addResourceHandler("/images/**").addResourceLocations("/WEB-INF/images/")
            .setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
}

Step 3: Run program and go to browser http://localhost:8080/images/logo.png

If your set contextRoot http://localhost:8080/project/images/logo.png

Full Code:

@SpringBootApplication
public class MainApplication implements WebMvcConfigurer {

    private static Logger logger = LoggerFactory.getLogger(MainApplication.class.getName());

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        // Register resource handler for images
        registry.addResourceHandler("/images/**").addResourceLocations("/WEB-INF/images/")
                .setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
    }

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

Work for me.


Additional

Or you can set below, If you want using in resources folder.

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

    registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/statics/")
            .setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
}

Because after deploy project structure below.

enter image description here

http://localhost:8080/images/logo.png

or

http://localhost:8080/project/images/logo.png

Sorry for English.


in your application properties file set the following line :

spring.resources.static-locations=file:///c:/{yourWorkSpace}/{projectName}/src/main/resources/static/

this is tested.