새소식

반응형
Java/Spring

Spring Boot 정적 리소스 설정

  • -
반응형

환경 : Spring Boot3, Java17, Thymeleaf, dialect layout

 

Spring Boot 에서 Thymeleaf 를 사용하여 axios 라이브러리를 script 태그를 통해 import 시키려다가

파일을 찾질 못해서 작성하게 됐다.

 

✅ 1. 기본 동작: /static/** → /로 매핑됨

Spring Boot 는 아래 디렉토리들을 기본적으로 정적 리소스 루트로 인식한다.

  • src/main/resources/static
  • src/main/resources/public
  • src/main/resources/resources
  • src/main/resources/META-INF/resources

예를 들어 아래 위치에 JS 파일이 있다고 가정하면

src/main/resources/static/js/app.js

 

👉 브라우저에서 접근 가능한 경로는:

http://localhost:8080/js/app.js

 

 

✅ 2. Thymeleaf에서 <script th:src>로 불러오기

<html xmlns:th="http://www.thymeleaf.org">
	<script th:src="@{/js/app.js}"></script>
</html

 

  • @{...} 표현식을 사용하면 Thymeleaf 가 context-path 포함하여 자동으로 URL 을 생성한다.
  • 예를 들어 context-path 가 "/" 일 경우 실제 HTML 은 아래처럼 렌더링 된다.
<script src="/js/app.js"></script>

 

✅ 3. application.yml / application.properties 에서 별도 설정은 필요 없음

정적 리소스를 src/main/resources/static 기본 경로에 잘 넣었다면 별도의 application.yml 설정은 필요없다.

 

✅ 4. 만약 정적 경로를 커스터마이징하고 싶다면?

application.yml 에 spring.web.resources.static-locations: 를 통해서 설정해주면 된다.

spring:
  web:
    resources:
      static-locations: classpath:/static/, classpath:/custom/

 

이렇게 되면 src/main/resouces/ 하위에 /static 경로와 /custom 경로의 파일도 접근할 수 있게 된다.

 

 

✅ 5. spring.web.resources.static-locations VS spring.mvc.static-path-pattern

 

✅ 핵심 차이

설정값 목적 예시 설명
spring.web.resources.static-locations 정적 리소스를 어디서 읽을지 지정 classpath: /static/ JS/CSS/이미지를 어느 폴더에서 가져올지 결정
spring.mvc.static-path-pattern 정적 리소스를 어떤 경로로 노출할지 설정 /static/** 브라우저에서 서버로 요청할 시 어떤 패턴으로 파일을 접근할지 결정

 

✅ 예시로 이해하기

src/main/resources/static/js/app.js

 

✅ 기본 설정 (아무 설정 없음)

  • static-locations: classpath: /static/
  • static-path-pattern: /**
  • 브라우저 URL : http://localhost:8080/js/app.js

✅ 1. static-path-pattern 변경

spring:
  mvc:
    static-path-pattern: /resources/**

 

  • 요청 URL : http://localhost:8080/resources/js/app.js
  • 내부 파일 경로 : classpath: /static/js/app/js

👉 결론 : 요청 경로만 바뀐다. 파일 실제 위치는 그대로이다.

 

✅ 2. static-locations 변경

spring:
  web:
    resources:
      static-locations: classpath:/public-assets/

 

  • 요청 URL : http://localhost:8080/js/app.js (기본 path pattern)
  • 내부 파일 경로 : src/main/resources/public-assets/js/app.js

👉 결론: 실제 파일 위치가 바뀜. 요청 경로는 기본 그대로 유지.

 

✅ 둘 다 바꾸면?

spring:
  mvc:
    static-path-pattern: /static/**
  web:
    resources:
      static-locations: classpath:/public-assets/

 

  • 파일 위치 : src/main/resources/public-assets/js/app.js
  • URL 경로 : http://localhost:8080/static/js/app.js

✅ 언제 뭘 써야 하나?

목적 설정값
리소스 파일의 물리적 위치를 바꾸고 싶다 spring.web.resources.static-locations
브라우저가 접근하는 URL 패턴을 바꾸고 싶다 spring.mvc.static-path-pattern

 

 

🔚 정리

  • spring.web.resources.static-locations : 서버가 리소스를 어디서 찾을까?
  • spring.mvc.static-path-pattern : 클라이언트가 브라우저를 통해 서버로 정적 리소스를 요청할 때 어떤 경로로 요청할까?

 

 

 

 

 

 

 

반응형
Contents