Hatem Jaber
Hatem Jaber

Reputation: 2402

Spring Boot Static Resources From Controllers and Other Classes

I've been trying to solve this issue and I can't find the answer.

I've been having to use src/main/resources/public/whatever... in order to access static resources from class files. I was under the impression that if you use /static /public /resources... that Spring Boot already has those paths configured.

I'm lost at this point and not sure how I can access these files without having to prepend src/main/resources/public.

EDIT

Based on the suggestions regarding the static content, I created a private directory to protect files etc... that I don't want publicly available. And left css, images, etc... in the /public folder.

Thank you all for the suggestions and recommendations, I appreciate it!

Upvotes: 1

Views: 680

Answers (3)

Pavel  Raev
Pavel Raev

Reputation: 19

Spring Boot expect you to use for content served directly src/main/resources/static

and to use for templating src/main/resources/templates

Upvotes: 1

whistling_marmot
whistling_marmot

Reputation: 3893

The directories you list, /static, /public and /resources, are for static content that will be served up by a web-application. Things like javascript files and images that will always be the same no matter who requests them and when, as opposed to JSPs for example that need to be processed on the server per request.

If you need to access a configured property in one of your Java classes (it must be a Spring bean), then you can put it in your application.properties file, and have Spring inject it using the @Value annotation.

Example code from Spring docs:

import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}

Upvotes: 1

Hatem Jaber
Hatem Jaber

Reputation: 2402

After more searching I ran across an example that used the ClassLoader. I've only been using Spring for a short time and not aware of all the tools that are available, there might be a better way than this; if so please tell let me know.

ClassLoader classLoader = getClass().getClassLoader()
new File(classLoader.getResource('public/file-name-or-directory').getFile())

So far it looks like it's working, I need to do some further testing and will post back if any issues.

Upvotes: 1

Related Questions