본문 바로가기
Baeldung번역&공부/Spring-Reactive

Spring WebFlux - 정적 컨텐츠들

by ms727 2025. 2. 18.

원본 글: https://www.baeldung.com/spring-webflux-static-content

이미지, HTML, CSS, Javascript 파일과 같은 정적 컨텐츠들을 웹 애플리케이션에서 제공해야할 때가 있습니다.

이 글에서는 Spring WebFlux에서 어떻게 정적 컨텐츠들을 제공하는지 학습합니다.

1. Overriding the Default Configuration

Spring Boot에서는 정적 컨텐츠들을 다음과 같은 경로에서 제공하고 있습니다.

  • /public
  • /static
  • /resoucre
  • /META-INF/resources

만약 Spring WebFlux에서 위의 경로들을 바꾸고 싶으면 appliction.properties에서 수정해줍니다.

spring.webflux.static-path-pattern=/assets/**

위와같이 설정하면 정적 리소스들은 모두 [/assets/] 디렉터리 하위에 존재함을 명시합니다.

하지만 @EnableWebFlux 어노테이션이 있으면 위 설정은 적용되지 않습니다.
왜냐하면 @EnableWebFlux를 사용하면 Spring Boot의 기본 정적 리소스 서빙 기능이 비활성화되기 때문입니다.

2. Routing Example

WebFlux에서 제공하는 라우팅 메커니즘을 통해 정적 리소스를 전달할 수 있습니다.

index.html을 반환하는 예제를 작성합니다.

@Configuration
public class RoutingExample {

    @Bean
    public RouterFunction<ServerResponse> htmlRouter(
            @Value("classpath:/public/index.html") Resource html) {
        return route(GET("/"), request -> ok().contentType(MediaType.TEXT_HTML).syncBody(html));
    }

}

참고로 원본글에 쓰인 syncBody()는 deprecated되었기에 bodyValue()함수를 쓰길 권장합니다.

또한 정적 리소스 저장 경로를 따로 지정할 수 있습니다. src/main/resources/img 디렉터리에 있는 이미지를 가져오는 코드를 작성해보겠습니다.

@Bean
public RouterFunction<ServerResponse> imgRouter() {
    return RouterFunctions.resources("/img/**", new ClassPathResource("img/"));
}

3. Custom Web Resources Path Example

정적 리소스를 저장하고 보여주는 다른 방법으로는 maven-resources-plugin을 사용한 방법과 Spring WebFlux property를 이용한 방법이 있습니다.

<plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <id>copy-resources</id>
            <phase>validate</phase> <!-- validate 단계에서 실행 -->
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <resources>
                    <resource>
                        <directory>src/main/assets</directory>  <!-- 원본 디렉토리 -->
                        <filtering>true</filtering>  <!-- 필터링 사용 가능 -->
                    </resource>
                </resources>
                <outputDirectory>${basedir}/target/classes/assets</outputDirectory> <!-- 복사 위치 -->
            </configuration>
        </execution>
    </executions>
</plugin>

pom.xml에 이렇게 추가하고,

spring.resources.static-locations=classpath:/assets/

이렇게 properties를 설정하면 index.html은 http:localhost:8080/index.html로 접근이 가능합니다. src/main/assets안에 보통 index.html을 두는데 이를 target/classes/assets으로 복사하고 properties의 적혀있는 /assets/를 새로운 정적리소스 기본경로로 지정하기 때문입니다.

4. 결론

이 글에서는 Spring Webflux를 이용해서 정적 컨텐츠를 저장하는 방법에 대해 학습하였습니다.

예제코드