↩뒤로가기

웹 환경 추가

웹 스코프는 웹 환경에서만 동작하므로 web 환경이 동작하도록 라이브러리를 추가해야 한다.

build.gradle에 추가

//web 라이브러리 추가
	implementation 'org.springframework.boot:spring-boot-starter-web'

이제 hello.core.CoreApplication 의 main 메서드를 실행하면 웹 애플리케이션이 실행되는 것을 확인할 수 있다.

Tomcat started on port(s): 8080 (http) with context path ''
Started CoreApplication in 0.914 seconds (JVM running for 1.528)

<aside> ⚠️ 참고: spring-boot-starter-web 라이브러리를 추가하면 스프링 부트는 내장 톰켓 서버를 활용해서 웹 서버와 스프링을 함께 실행시킨다.

</aside>

<aside> ⚠️ 참고: 스프링 부트는 웹 라이브러리가 없으면 우리가 지금까지 학습한 AnnotationConfigApplicationContext 을 기반으로 애플리케이션을 구동한다. 웹 라이브러리가 추가되면 웹과 관련된 추가 설정과 환경들이 필요하므로 AnnotationConfig**ServletWebServer**ApplicationContext 를 기반으로 구동한다.

</aside>

만약 기본 포트인 8080 포트를 다른곳에서 사용중이어서 오류가 발생하면 포트를 변경해야 한다. 9090 포트로 변경하려면 application.properties 파일에 다음 설정을 추가하자.

server.port=9090

request 스코프 예제 개발

동시에 여러 HTTP 요청이 오면 정확히 어떤 요청이 남긴 로그인지 구분하기 어렵다. 이럴 때 사용하기 좋은 것이 바로 request 스코프이다.

다음과 같이 로그가 남도록 request 스코프를 활용해 추가 기능을 해발해보자.

[d06b992f...] request scope bean create
[d06b992f...][<http://localhost:8080/log-demo>] controller test
[d06b992f...][<http://localhost:8080/log-demo>] service id = testId
[d06b992f...] request scope bean close

기대하는 공통 포멧: [UUID][requestURL]{message}

UUID를 사용해서 HTTP 요청을 구분하자.

requestURL 정보도 추가로 넣어서 어떤 URL을 요청해서 남은 로그인지 확인하자.

package hello.core.common;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.UUID;

@Component
@Scope(value = "request")
public class MyLogger {

    private String uuid;
    private String requestURL;

    public MyLogger(String requestURL) {
        this.requestURL = requestURL;
    }

    public void log(String message){
        System.out.println("[" + uuid + "] [" + requestURL + "] {" + message + "}");
    }

    @PostConstruct
    public void ini(){
        uuid = UUID.randomUUID().toString();
        System.out.println("[" + uuid + "] request scope bean create!" + this);
    }

    @PreDestroy
    public void close(){
        System.out.println("[" + uuid + "] request scope bean close!" + this);
    }

    public void setRequestURL(String requestURL) {
        this.requestURL = requestURL;
    }
}

로그를 출력하기 위한 MyLogger 클래스이다.