user3556304
user3556304

Reputation: 1037

How to add the static resources in Spring-boot by annotation?

Besides the pre-determined folders (such as /static/), is there any way to configure Spring Boot (not by XML) to specify the locations of static resources?

For example, starting from this guide, we add another image file, test1.jpg, as our static resource.

Here is the final directory structure:

└── src
   └── main
       └── java
           └── hello
               └── Application.java 
               └── GreetingController.java
       └── resources
           └── templates
               └── greeting.html
           └── assets
               └── img
                   └── test1.jpg

We did not change any java code from this guide , but only add one additional line in greeting.html :

<img src="test1.jpg" />

Nevertheless, our greeting.html still cannot find test1.jpg.

Could someone give us some suggestions?

Thanks!!

Upvotes: 0

Views: 233

Answers (1)

Dave Syer
Dave Syer

Reputation: 58094

You can add a @Bean of type WebMvcConfigurerAdapter and set the paths yourself, e.g.

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

Why not just use the defaults though?

Upvotes: 2

Related Questions