HTTP ServletResponse 역할

HTTP 응답 메시지 생성

  • HTTP 응답코드 지정
  • 헤더 생성
  • 바디 생성
@WebServlet(name = "responseHeaderServlet", urlPatterns = "/response-header")
public class ResponseHeaderServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //[status-line]
        response.setStatus(HttpServletResponse.SC_OK);

        //[response-headers]
        response.setHeader("Content-Type", "text/plain;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("my-header", "hello");

        //[Header 편의 메서드]
//        content(response);
//        cookie(response);
        redirect(response);


        PrintWriter writer = response.getWriter();
        writer.println("ok");
    }

    private void content(HttpServletResponse response) {
        //Content-Type: text/plain;charset=utf-8
        //Content-Length: 2
//        response.setHeader("Content-Type", "text/plain;charset=utf-8");
        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
//        response.setContentLength(2); //(생략시 자동 생성)
    }

    private void cookie(HttpServletResponse response) {
        //Set-Cookie: myCookie=good; Max-Age=600;
        //response.setHeader("Set-Cookie", "myCookie=good; Max-Age=600");
        Cookie cookie = new Cookie("myCookie", "good");
        cookie.setMaxAge(600); //600초
        response.addCookie(cookie);
    }

    private void redirect(HttpServletResponse response) throws IOException {
        //Status Code 302
        //Location: /basic/hello-form.html

//        response.setStatus(HttpServletResponse.SC_FOUND); //302
//        response.setHeader("Location", "/basic/hello-form.html");
        response.sendRedirect("/basic/hello-form.html");
    }
}

 

 

 

 

강의출처 : https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

HTTP 요청 데이터 개요

주로 3가지 방법을 사용한다.

GET - 쿼리 파라미터

  • /url?username=hello&age=20
  • 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함해서 전달
  • 예) 검색, 필터, 페이징 등에서 많이 사용

POST - HTML From

  • content-type : application/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파라미터 형식으로 전달 username=hello&age=20
  • 예) 회원가입, 상품 주문, HTML Form 사용

HTTP message body에 데이터를 직접 담아서 요청

  • HTTP API에서 주로 사용 => JSON, XML, TEXT
  • 데이터 형식은 주로 JSON 사용
  • POST, PUT, PAATCH 등 사용

HTTP 요청 데이터 - GET 쿼리 파라미터

URL

http://localhost:8080/request-param?username=hello1&username=hello2&age=20

코드

@WebServlet(name = "requestParamServlet", urlPatterns = "/request-param")
public class RequestParamServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("--- 전체 조회 start ---");
        request.getParameterNames().asIterator()
                .forEachRemaining(pramName -> System.out.println(pramName + " = " + request.getParameter(pramName)));
        System.out.println("--- 전체 조회 end ---");
        System.out.println();

        System.out.println("--- 단일 조회 start ---");
        String username = request.getParameter("username");
        String age = request.getParameter("age");

        System.out.println("username = " + username);
        System.out.println("age = " + age);
        System.out.println("--- 단일 조회 end ---");
        System.out.println();

        System.out.println("--- 중복 이름 조회 start ---");
        String[] usernames = request.getParameterValues("username");
        for (String name : usernames) {
            System.out.println("name = " + name);
        }
        System.out.println("--- 중복 이름 조회 end ---");
    }

}

결과

--- 전체 조회 start ---
username = hello1
age = 20
--- 전체 조회 end ---

--- 단일 조회 start ---
username = hello1
age = 20
--- 단일 조회 end ---

--- 중복 이름 조회 start ---
name = hello1
name = hello2
--- 중복 이름 조회 end ---

 

HTTP 요청 데이터 - POST HTML Form

특징

  • content-type : application/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파라미터 형식으로 데이터를 전달한다.

html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/request-param" method="post">
    username: <input type="text" name="username" />
    age:      <input type="text" name="age" />
    <button type="submit">전송</button>
</form>
</body>
</html>

 

결과

--- 전체 조회 start ---
username = user
age = 20
--- 전체 조회 end ---

--- 단일 조회 start ---
username = user
age = 20
--- 단일 조회 end ---

--- 중복 이름 조회 start ---
name = user
--- 중복 이름 조회 end ---

HTTP 요청 데이터 - API 메시지 바디 - 단순 텍스트

@WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-body-string")
public class RequestBodyStringServlet extends HttpServlet {

    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        System.out.println("messageBody = " + messageBody);

        response.getWriter().write("ok");
    }
}

HTTP 요청 데이터 - API 메시지 바디 - JSON

@Setter
@Getter
@ToString
public class HelloData {

    private String username;
    private int age;
}
@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json")
public class RequqestBodyJsonServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        System.out.println("messageBody = " + messageBody);

        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
        System.out.println("helloData.getUsername() = " + helloData.getUsername());
        System.out.println("helloData.getAge() = " + helloData.getAge());
    }

}

강의출처 : https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

Servlet 프로젝트 생성

@ServletComponentScan // 서블릿 자동 등록
@SpringBootApplication
public class ServletApplication {

   public static void main(String[] args) {
      SpringApplication.run(ServletApplication.class, args);
   }

}

@ServletComponentScan : 하위 패키지를 스캔하며 Servlet을 찾는다.

@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("HelloServlet.service");
        
        System.out.println("request = " + request);
        System.out.println("response = " + response);
        
        String username = request.getParameter("username");
        System.out.println("username = "+ username);
        
        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
        
        response.getWriter().write("hello " + username);

    }

HTTP 요청 메시지 로그 남기기

logging.level.org.apache.coyote.http11=debug

HTTP Servlet Request

HTTP Servlet Request역할

  • HTTP 요청 메시지를 개발자가 직접 파싱해서 사용해도 되지만, 매우 불편하다. 서블릿은 개발자가 HTTP 요청 메시지를 편리하게 사용 할 수 있도록 개발자 대신에 HTTP 요청 메시지를 파싱한다. 그리고 그 결과를 HttpServletRequest객체에 담아서 제공한다.
@WebServlet(name = "requestHeaderServlet", urlPatterns = "/request-header")
public class RequestHeaderServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        printStartLine(request);
        printHeaders(request);
        printHeaderUtils(request);
        printEtc(request);
    }


    private void printStartLine(HttpServletRequest request) {
        System.out.println("--- REQUEST-LINE - start ---");

        System.out.println("request.getMethod() = " + request.getMethod()); //GET
        System.out.println("request.getProtocal() = " + request.getProtocol()); //HTTP/1.1
        System.out.println("request.getScheme() = " + request.getScheme()); //http
        // http://localhost:8080/request-header
        System.out.println("request.getRequestURL() = " + request.getRequestURL());
        // /request-test
        System.out.println("request.getRequestURI() = " + request.getRequestURI());
        //username=hi
        System.out.println("request.getQueryString() = " + request.getQueryString());
        System.out.println("request.isSecure() = " + request.isSecure()); //https 사용 유무
        System.out.println("--- REQUEST-LINE - end ---");
        System.out.println();
    }

    //Header 모든 정보
    private void printHeaders(HttpServletRequest request) {
        System.out.println("--- Headers - start ---");

/*
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println(headerName + ": " + headerName);
        }
*/

        request.getHeaderNames().asIterator()
                .forEachRemaining(headerName -> System.out.println(headerName + ": " + headerName));

        System.out.println("--- Headers - end ---");
        System.out.println();
    }

    private void printHeaderUtils(HttpServletRequest request) {
        System.out.println("--- Header 편의 조회 start ---");
        System.out.println("[Host 편의 조회]");
        System.out.println("request.getServerName() = " + request.getServerName()); //Host 헤더
        System.out.println("request.getServerPort() = " + request.getServerPort()); //Host 헤더
        System.out.println();

        System.out.println("[Accept-Language 편의 조회]");
        request.getLocales().asIterator()
                .forEachRemaining(locale -> System.out.println("locale = " + locale));
        System.out.println("request.getLocale() = " + request.getLocale());
        System.out.println();

        System.out.println("[cookie 편의 조회]");
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                System.out.println(cookie.getName() + ": " + cookie.getValue());
            }
        }
        System.out.println();

        System.out.println("[Content 편의 조회]");
        System.out.println("request.getContentType() = " + request.getContentType());
        System.out.println("request.getContentLength() = " + request.getContentLength());
        System.out.println("request.getCharacterEncoding() = " + request.getCharacterEncoding());

        System.out.println("--- Header 편의 조회 end ---");
        System.out.println();
    }

    //기타 정보
    private void printEtc(HttpServletRequest request) {
        System.out.println("--- 기타 조회 start ---");

        System.out.println("[Remote 정보]");
        System.out.println("request.getRemoteHost() = " + request.getRemoteHost()); //
        System.out.println("request.getRemoteAddr() = " + request.getRemoteAddr()); //
        System.out.println("request.getRemotePort() = " + request.getRemotePort()); //
        System.out.println();

        System.out.println("[Local 정보]");
        System.out.println("request.getLocalName() = " + request.getLocalName()); //
        System.out.println("request.getLocalAddr() = " + request.getLocalAddr()); //
        System.out.println("request.getLocalPort() = " + request.getLocalPort()); //

        System.out.println("--- 기타 조회 end ---");
        System.out.println();
    }
}

강의출처 : https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

스레드

  • 애플리케이션 코드를 하나하나 순차적으로 실행하는것
  • 자바 메인 메소드를 처음 실행하면 main이라는 이름의 스레드가 실행
  • 스레드가 없다면 자바 애플리케이션 실행이 불가능
  • 스레드는 한번에 하나의 코드 라인만 수행
  • 동시 처리가 필요하면 스레드를 추가로 생성

  • 다중요청시 요청1이 완료되기까지 요청2가 대기해야한다.

  • 요청 마다 스레드를 생성하는 방법

요청마다 스레드 생성의 장단점

장점

  • 동시 요청을 처리 할 수 있다.
  • 리소스(CPU, 메모리)가 허용할때 까지 처리가능
  • 하나의 스레드가 지연되어도, 나머지 스레드는 정상 동작한다.

단점

  • 스레드는 생성비용이 매우 비싸다.
    • 고객의 요청이 올때 마다 스레드를 생성하면, 응답 속도가 늦어진다.
  • 스레드는 컨텍스트 스위칭 비용이 발생한다.
  • 스레드 생성에 제한이 없다.
    • 고객요청이 너무 많이오면, CPU, 메모리 임계점을 넘어서 서버가 죽을 수 있다.

스레드 풀

요청마다 스레드 생성의 단점 보완

특징

  • 필요한 스레드를 스레드 풀에 보관하고 관리한다.
  • 스레드 풀에 생성가능한 스레드의 최대치를 관리한다. 톰캣은 최대 200개 기본설정(변경가능)

사용

  • 스레드가 필요하면, 이미 생성되어 있는 스레드를 스레드 풀에서 꺼내서 사용한다.
  • 사용을 종료하면 스레드 풀에 해당 스레드를 반납한다.
  • 최대 스레드가 모두 사용중이어서 스레드 풀에 스레드가 없으면 기다리는 요청은 거절하거나 특정 숫자만큼 대기하도록 설정 가능하다.

장점

  • 스레드가 미리 생성되어 있으므로, 스레드를 생성하고 종료하는 비용(CPU)이 절약되고, 응답 시간이 빠르다.
  • 생성가능한 스레드의 최대치가 있으므로 너무많은 요청이 들어와도 기존 요청은 안전하게 처리할 수 있다.

실무팁

  • WAS의 주요 튜닝 포인트는 최대 스레드(Max Thread)수 이다.
  • 이 값을 너무 낮게 설정하면
    1. 동시 요청이 많으면, 서버 리소스는 여유롭지만, 클라이언트는 금방 응답 지연
    2. ex) 스레드 10개 설정, 클라이언트요청 100개시 CPU는 5% 사용만한다.
  • 이값을 너무 높게 설정하면
    1. 동시 요청이 많으면 CPU, 메모리의 리소스 임계점 초과로 서버 다운
  • 장애 발생시
    1. 클라우드면 일단 서버부터 늘리고, 이후에 튜닝
    2. 클라우드가 아니면 열심히 튜닝

스레드풀의 적정 숫자

  • 애플리케이션 로직의 복잡도, CPU, 메모리, IO 리소스 상황에 다라 모두 다름
  • 성능 테스트로 최대한 실제 서비스와 유사하게 성능 테스트 시도

WAS의 멀티 스레드 지원

멀티 스레드에 대한 부분은 WAS가 처리

개발자가 멀티 스레드 관련 코드를 신경쓰지 않아도 된다.

개발자는 마치 싱글 스레드 프로그래밍을 하듯이 편리하게 소스 코드를 개발

멀티 스레드 환경이므로 싱글톤 객체(서블릿, 스프링 빈)는 주의해서 사용

 

 

강의출처 : https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

서블릿

특징

urlPatterns(hello)의 URL이 호출되면 서블릿 코드가 실행

HTTP 요청 정보를 편리하게 사용 할 수 있는 HttpServletRequest

HTTP 응답 정보를 편리하게 제공 할 수 있는 HttpServletResponse

개발자는 HTTP 스펙을 매우 편리하게 사용

서블릿 컨테이너

  • 톰캣처럼 서블릿을 지원하는 WAS를 서블릿 컨테이너라고한다.
  • 서블릿 컨테이너는 서블릿 객체를 생성, 초기화, 종료하는 생명주기를 관리한다.
  • 서블릿 객체는 싱글톤으로 관리
    1. 고객의 요청이 올 때 마다 계속 객체를 생성하는것은 비효율
    2. 최초 로딩 시점에 서블릿 객체를 미리 만들어두고 재활용
    3. 모든 고객 요청은 동일한 서블릿 객체 인스턴스에 접근
    4. 공유 변수 사용 주의
    5. 서블릿 컨테이너 종료시 함께 종료
  • JSP도 서블릿으로 변환 되어서 사용
  • 동시 요청을 위한 멀티 스레드 처리 지원

 

 

강의출처 : https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

스프링 컨테이너에 프로토타입 스코프의 빈을 요청하면 항상 새로운 객체 인스턴스를 생성해서 반환한다. 하지만 싱글톤 빈과 함께 사용할때는 의도한 대로 잘 동작하지 않으므로 주의해야한다.

프로토타입 빈 직접요청

  • 클라이언트A는 스프링 컨테이너에 프로토타입 빈을 요청한다.
  • 스프링 컨테이너는 프로토타입 빈을 새로 생성해서 반환한다. 해당빈의 count 필드 값은 0이다.
  • 클라이언트는 조회한 프로토타입 빈에 addCount()를 호출하면서 count 필드값을 ++한다.
  • 결과적으로 프로토타입 빈의 count는 1이된다.

Test

public class SingletonWithPrototypeTest1 {

    @Test
    void prototypeFind(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        prototypeBean1.addCount();
        Assertions.assertThat(prototypeBean1.getCount()).isEqualTo(1);

        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        prototypeBean2.addCount();
        Assertions.assertThat(prototypeBean2.getCount()).isEqualTo(1);

    }

    @Scope("prototype")
    static class PrototypeBean{
        private int count;
        public void  addCount(){
            count++;
        }
        public int getCount(){
            return count;
        }
        @PostConstruct
        public void init(){
            System.out.println("PrototypeBean.init " + this);
        }
        @PreDestroy
        public void destroy(){
            System.out.println("PrototypeBean.destroy");
        }
    }
}

 

결과

 

21:39:22.329 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6c80d78a
21:39:22.359 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
21:39:22.404 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
21:39:22.407 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
21:39:22.408 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
21:39:22.410 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
PrototypeBean.init hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean@4d14b6c2
PrototypeBean.init hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean@6950ed69

Process finished with exit code 0

 

▶ 프로토타입빈의 당연한결과이다.

 

싱글톤 빈에서 프로토타입 빈 사용

clientBean이라는 싱글톤이 의존관계 주입을 통해서 프로토타입 빈을 주입받아서 사용하는예이다.

1. clientBean은 싱글톤이므로, 보통 스프링 컨테이너 생성시점에 함께 생성되고, 의존관계 주입도 받는다.

2. clientBean은 의존관계 자동 주입을 사용한다. 주입시점에 스프링 컨테이너에 프로토타입 빈을 요청한다.

3. 스프링 컨테이너는 프로토타입 빈을 생성해서 clientBean에 반환한다. 프로토타입 빈의 count 필드값은 0이다.

4. 이제 clientBean은 프로토타입 빈을 내부 필드에 보관(참조)한다.

5. 클라이언트A는 clientBean을 스프링 컨테이너에 요청해서 받는다. 싱글톤이므로 항상 같은 clientBean이 반환된다.

6. 클라이언트 A는 clientBean.logic()을 호출한다.

7. clientBean은 prototypeBean의 addCount()를 호출해서 프로토타입 빈의 count를 증가한다. count값이 1이된다.

8. 클라이언트B는 clientBean을 스프링 컨테이너에 요청해서 받는다. 싱글톤이므로 항상 같은 clientBean이 반환된다.

9. 여기서 중요한 점이있는데, clientBean이 내부에 가지고 있는 프로토타입 빈은 이미 과거에 주입이 끝난 빈이다. 주입시점에 스프링 컨테이너에 요청해서 프로토타입 빈이 새로 생성이 된것이지, 사용할때마다 새로 생성되는 것이 아니다.

10. 클라이언트B는  clientBean.logic() 을 호출한다.

11. clientBean은 prototypeBean의 addCount() 를 호출해서 프로토타입 빈의 count를 증가한다. 원래 값이 1이기때문에 2가된다.

 

Test

public class SingletonWithPrototypeTest1 {

    @Test
    void prototypeFind(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        prototypeBean1.addCount();
        assertThat(prototypeBean1.getCount()).isEqualTo(1);

        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        prototypeBean2.addCount();
        assertThat(prototypeBean2.getCount()).isEqualTo(1);

    }

    @Test
    void singletonClientUsePrototype(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);

        ClientBean clientBean1 = ac.getBean(ClientBean.class);
        int count1 = clientBean1.logic();
        assertThat(count1).isEqualTo(1);

        ClientBean clientBean2 = ac.getBean(ClientBean.class);
        int count2 = clientBean2.logic();
        assertThat(count2).isEqualTo(2);

    }

    @Scope("singleton")
    @RequiredArgsConstructor
    static class ClientBean{
        private final PrototypeBean prototypeBean;

        public int logic(){
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }

    }

    @Scope("prototype")
    static class PrototypeBean {
        private int count;

        public void addCount() {
            count++;
        }

        public int getCount() {
            return count;
        }

        @PostConstruct
        public void init() {
            System.out.println("PrototypeBean.init " + this);
        }

        @PreDestroy
        public void destroy() {
            System.out.println("PrototypeBean.destroy");
        }
    }
}

결과

22:09:53.247 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1a451d4d
22:09:53.285 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
22:09:53.329 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
22:09:53.337 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
22:09:53.339 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
22:09:53.342 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
22:09:53.361 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'singletonWithPrototypeTest1.ClientBean'
PrototypeBean.init hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean@7bd7d6d6
22:09:53.396 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'singletonWithPrototypeTest1.ClientBean' via constructor to bean named 'singletonWithPrototypeTest1.PrototypeBean'

Process finished with exit code 0

 

  • 스프링은 일반적으로 싱글톤 빈을 사용하므로, 싱글톤 빈이 프로토타입 빈을 사용하게된다. 그런데 싱글톤 빈은 생성시점에만 의존관계 주입을 받기 때문에 프로토타입 빈이 새로 생성되기는 하지만, 싱글톤빈과 함께 계속 유지되는것이문제다.

▶ 이럴경우  프로토타입빈을 사용할필요가있을까? 그냥 싱글톤 빈을 사용하는게 더 효율적이라생각된다.

프로토타입 빈을 주입 시점에만 새로 생성하는게 아니라, 사용할 때 마다 새로 생성해서 사용하는 것을 원한다.

 

※ 여러빈에서 같은 프로토타입 빈을 주입 받으면, 주입 받는 시점에 각각 새로운 프로토타입 빈이 생성된다.

ex) clientA, clientB가 각각 의존관계 주입을 받으면 각각 다른 인스턴스의 프로토타입 빈을 주입 받는다.

clientA → prototypeBean@x01

clientB prototypeBean@x02

물론 사용할때 마다 새로 생성되는 것은 아니다.

 

프로토타입 스코프 - 싱글톤 빈과 함께 사용시 Provicer로 문제 해결

싱글톤 빈과 프로토타입 빈을 함께 사용 할 때, 어떻게 하면 사용할 때마다 항상 새로운 프로토 타입 빈을 생성 할 수 있을까?

    @Scope("singleton")
    static class ClientBean{

    @Autowired
    private ObjectProvider<PrototypeBean> prototypeBeanProvider;

        public int logic(){
            PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }
    @Test
    void singletonClientUsePrototype(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);

        ClientBean clientBean1 = ac.getBean(ClientBean.class);
        int count1 = clientBean1.logic();
        assertThat(count1).isEqualTo(1);

        ClientBean clientBean2 = ac.getBean(ClientBean.class);
        int count2 = clientBean2.logic();
        assertThat(count2).isEqualTo(1);
    }

ObjectProvider의 getObject()를 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다.

하지만 ObjectProvider는 ObjectFactory를 상속, 옵션, 스트림처리등 편의 기능이 많고, 별도의 라이브러리가 필요없으나, 스프링에

의존적이다.

JSR-330 Provider

라이브러리 추가 implementation 'javax.inject:javax.inject:1'  

   // Provider 라이브러리 추가
    @Scope("singleton")
    static class ClientBean{

        @Autowired
        private Provider<PrototypeBean> prototypeBeanProvider;

        public int logic(){
            PrototypeBean prototypeBean = prototypeBeanProvider.get();
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }

provider.get을 통해 항상 새로운 프로토타입 빈이 생성된다.

 

강의출처 : 스프링 핵심 원리 - 기본편 - 인프런 | 강의 (inflearn.com)

빈 스코프란?

스프링 빈이 스프링 컨테이너의 시작과 함께 생성되어 스프링 컨테이너가 종료될때 까지 유지된다.

이것은 스프링 빈이 기본적으로 싱글톤 스코프로 생성되기 때문이다. 

스프링은 다음과 같은 다양한 스코프를 지원한다.

  • 싱글톤 : 기본 스코프, 스프링 컨테이너의 시작과 종료까지 유지되는 가장 넓은 범위의 스코프이다.
  • 프로토타입 : 스프링 컨테이너는 프로토타입 빈의 생성과 의존관계 주입까지만 관여하고 더는 관리하지 않는 매우 짧은 범위의 스코프이다.
  • 웹 관련 스코프 
    • request : 웹 요청이 들어오고 나갈때 까지 유지되는 스코프이다.
    • session : 웹 세선이 생성되고 종료될때까지 유지되는 스코프이다.
    • application : 웹의 서블릿 컨텍스트와 같은 범위로 유지되는 스코프이다.

싱글톤 스코프

  1. 싱글톤 스코프의 빈을 스프링컨테이너에 요청한다.
  2. 스프링 컨테이너는 본인이 관리하는 스프링 빈을 반환한다.
  3. 이후에 스프링 컨테이넝에 같은 요청이와도 같은 객체 인스턴스 빈을 반환한다.

▶ 기존에 알고있던 싱글톤 방식이다.

 

Test

public class SingletonTest {

    @Test
    void singletonBeanTest() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SingletonTest.class);

        SingletonTest singletonBean1 = ac.getBean(SingletonTest.class);
        SingletonTest singletonBean2 = ac.getBean(SingletonTest.class);
        System.out.println("singletonBean1 = " + singletonBean1);
        System.out.println("singletonBean2 = " + singletonBean2);
        Assertions.assertThat(singletonBean1).isSameAs(singletonBean2);
    }

    @Scope("singleton")
    static class SingletonBean{
        @PostConstruct
        public void init(){
            System.out.println("SingletonBean.init");
        }

        @PreDestroy
        public void destroy() {
            System.out.println("SingletonBean.destroy");
        }
    }
}

 

결과

SingletonBean.init
singletonBean1 = hello.core.scope.SingletonTest$SingletonBean@5884a914
singletonBean2 = hello.core.scope.SingletonTest$SingletonBean@5884a914
20:29:08.921 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6c80d78a, started on Thu Mar 30 20:29:08 KST 2023
SingletonBean.destroy

 

▶ 초기화 실행 및 싱글톤 빈생성, 종료 까지 실행이된다!

프로토타입 빈 스코프

1. 프로토타입 스코프의 빈을 스프링 컨테이너에 요청한다.

2. 스프링 컨테이너는 이 시점에 프로토타입 빈을 생성하고, 필요한 의존관계를 주입한다.

▶ 요청시 마다 새로운 빈을 생성한다.

 

3. 스프링 컨테이너는 생성한 프로토타입 빈을 클라이언트에게 반환한다.

4. 이후에 스프링 컨테이너에 같은 요청이 오면 항상 새로운 프로토타입 빈을 생성해서 반환한다.

 

스프링 컨테이너는 프로토타입 빈을 생성하고, 의존관계 주입, 초기화까지만 처리한다. 클라이언트에게 빈을 반환하고, 이후 스프링 컨테이너는 생성된 프로토타입 빈을 관리하지 않는다. 프로토타입 빈을 관리할 책임은 프로토타입 빈을 받은 클라이언트에게 있다. 그래서 '@PreDestory'같은 종료메서드가 호출되지 않는다.

 

Test

public class PrototypeTest {

    @Test
    void prototypeBeanTest() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);

        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        System.out.println("PrototypeBean1 = " + prototypeBean1);
        System.out.println("PrototypeBean2 = " + prototypeBean2);

        Assertions.assertThat(prototypeBean1).isNotSameAs(prototypeBean2);
        ac.close();
    }

    @Scope("prototype")
    static class PrototypeBean{
        @PostConstruct
        public void init(){
            System.out.println("PrototypeBean.init");
        }

        @PreDestroy
        public void destroy() {
            System.out.println("PrototypeBean.destroy");
        }
    }
}

결과

PrototypeBean.init
PrototypeBean.init
PrototypeBean1 = hello.core.scope.PrototypeTest$PrototypeBean@5884a914
PrototypeBean2 = hello.core.scope.PrototypeTest$PrototypeBean@50378a4
20:33:50.557 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6c80d78a, started on Thu Mar 30 20:33:50 KST 2023

 

▶ 개별 다른 빈이 생성, destory 종료 되지않는다. 

    종료를 해야할 경우 

prototypeBean1.destroy();
prototypeBean2.destroy();

직접 수동 종료시켜야한다.

웹스코프

웹 스코프의 특징

  • 웹 스코프는 웹 환경에서만 동작한다.
  • 웹 스코프는 프로토타입과 다르게 스프링이 해당 스코프의 종료시점까지 관리한다. 따라서 종료메서드가 호출된다.

웹 스코프의 종류

  • request : HTTP 요청 하나가 들어오고 나갈때까지 유지되는 스코프, 각각의 HTTP 요청마다 별도의 빈 인스턴스가 생성되고, 관리된다.
  • session : HTTP Session과 동일한 생명주기를 가지는 스코프
  • application : 서블릿 컨텍스트(ServletContext)와 동일한 생명주기를 가지는 스코프
  • websocket : 웹 소켓과 동일한 생명주기를 가지는 스코프

request 스코프 예제 만들기

웹 환경추가

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

implementation 'org.springframework.boot:spring-boot-starter-web'

▶ spring-boot-starter-web 라이브러리를 추가하면 스프링 부트는 내장 톰캣 서버를 활용해서 웹 서버와 스프링을 함께 실행시킨다.

 

2023-04-01 20:27:48.032  INFO 4488 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-04-01 20:27:48.041  INFO 4488 --- [           main] hello.core.CoreApplication               : Started CoreApplication in 2.977 seconds (JVM running for 3.74)

 

request 스코프 예제 개발

동시에 여러 HTTP 요청이 오면 정확히 어떤 요청이 남긴 로그인지 구분하기 어렵다.

이럴때 사용하기 딱 좋은것이 바로 request 스코프이다.

ex)

공통포맷 : [UUID][requestURL]{message}

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

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

 

MyLogger 

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

    private String uuid;
    private String requestURL;

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

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

    @PostConstruct
    public void init(){
        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);
    }
}

 

  • 로그를 출력하기위한 MyLogger 클래스이다.
  • @Scope(value = "request")를 사용해서 request 스코프로 지정했다. 이제 이 빈은 HTTP 요청 당 하나씩 생성되고 HTTP요청이 끝나는 시점에 소멸된다.
  • 이빈이 생성되는 시점에 자동으로 @PostConstruct 초기화 메서드를 사용해서 uuid를 생성해서 저장한다.
  • 이 빈은 HTTP요청 당 하나씩 생성되므로, uuid를 저장해두면 다른 HTTP요청과 구분할 수 있다.
  • 이빈이 소멸되는 시점에 @PreDestroy를 사용해서 종료 메서드를 남긴다.
  • requestURL은 이빈이 생성되는 시점에는 알 수 없으므로, 외부에서 setter로 입력 받는다.

LogDemoController

@Controller
@RequiredArgsConstructor
public class LogDemoController {

    private final LogDemoService logDemoService;
    private final MyLogger myLogger;

    @RequestMapping("log-demo")
    @ResponseBody
    public String logDemo(HttpServletRequest request){
        String requestURL = request.getRequestURL().toString();
        myLogger.setRequestURL(requestURL);
        myLogger.log("controller test");
        logDemoService.logic("testId");
        return "Ok";
    }
}
  • 로거가 잘 작동하는지 확인하는 테스트용 컨트롤러이다.
  • 여기서 HttpServletRequest를 통해서 요청 URL을 받았다.
    requestURL 값 : http://localhost:8080/log-demo
  • 이렇게 받은 requestURL 값을 myLogger에 저장해둔다. myLogger는  HTTP 요청당 각각 구분되므로 다른 HTTP 요청때문에 갑싱 섞이는 걱정은 하지 않아도 된다.
  • 컨트롤러에서 controller test라는 로그를 남긴다.

LogDemoService

@Service
@RequiredArgsConstructor
public class LogDemoService {

    private final MyLogger myLogger;
    public void logic(String id) {
        myLogger.log("service id = " + id);
    }
}
  • 비즈니스 로직이 있는 서비스 계층에서도 로그를 출력해보자.
  • 여기서 중요한점이 있다. request scope를 사용하지 않고 파라미터로 이 모든 정보를 서비스 계층에 넘긴다면, 파라미터가 많아서 지저분해진다. 더 문제는 requestURL같은 웹과 관련된 정보가 웹과 관련이 없는 서비스 계층까지 넘어가게 된다. 웹과 관련된 부분은 컨트롤러까지만 사용해야 한다. 서비스 계층은 웹 기술에 종속되지 않고, 가급적 순수하게 유지하는 것이 유지보수 관점에서 좋다.
  • reqeust scope의 MyLogger 덕분에 이런 부분을 파라미터로 넘기지않고, MyLogger의 멤버변수에 저장해서 코드와
    계층을깔끔히 유지 할 수 있다.

결과

Error creating bean with name 'myLogger': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton;

 

스프링 애플리케이션을 실행 시키면 오류가 발생한다. 스프링 애플리케이션을 실행하는 시점에 싱글톤 빈은 생성해서 주입이 가능하지만, reqeust 스코프빈은 아직 생성되지않는다. 이 빈은 실제 고객의 요청이 와야 생성 할 수 있다.

ObjectProvider

  • objectProvider : 지정된 빈을 컨테이너에 대신 찾아주는 DL 서비스를 제공

LogDemoController

@Controller
@RequiredArgsConstructor
public class LogDemoController {

    private final LogDemoService logDemoService;
    private final ObjectProvider<MyLogger> myLoggerProvider;

    @RequestMapping("log-demo")
    @ResponseBody
    public String logDemo(HttpServletRequest request){
        String requestURL = request.getRequestURL().toString();
        MyLogger myLogger = myLoggerProvider.getObject();
        myLogger.setRequestURL(requestURL);
        myLogger.log("controller test");
        logDemoService.logic("testId");
        return "Ok";
    }
}

LogDemoService

@Service
@RequiredArgsConstructor
public class LogDemoService {

    private final ObjectProvider<MyLogger> myLoggerProvider;
    public void logic(String id) {
        MyLogger myLogger = myLoggerProvider.getObject();
        myLogger.log("service id = " + id);
    }
}

결과

2023-04-01 21:07:19.560  INFO 9328 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-04-01 21:07:19.572  INFO 9328 --- [           main] hello.core.CoreApplication               : Started CoreApplication in 3.283 seconds (JVM running for 3.948)

 

URL요청

[9042288c-7f5d-4f15-8f64-823e23087d3e] request scope bean create : hello.core.common.MyLogger@31f135a
[9042288c-7f5d-4f15-8f64-823e23087d3e][http://localhost:8080/log-demo] controller test
[9042288c-7f5d-4f15-8f64-823e23087d3e][http://localhost:8080/log-demo] service id = testId
[9042288c-7f5d-4f15-8f64-823e23087d3e] request scope bean close : hello.core.common.MyLogger@31f135a

재요청

[ec91e362-6a53-41d8-ace1-01820edd9a61] request scope bean create : hello.core.common.MyLogger@6ef1316a
[ec91e362-6a53-41d8-ace1-01820edd9a61][http://localhost:8080/log-demo] controller test
[ec91e362-6a53-41d8-ace1-01820edd9a61][http://localhost:8080/log-demo] service id = testId
[ec91e362-6a53-41d8-ace1-01820edd9a61] request scope bean close : hello.core.common.MyLogger@6ef1316a

 

  • ObjectProvider 덕분에 ObjectProvider.getObject()를 호출하는 시점까지 request scope 빈의 생성을 지연 할 수 있다.
  • ObjectProvider.getObject()를 호출하는 시점에는 HTTP 요청이 진행중이므로 request scope 빈의 생성이 정상처리된다.
  • ObjectProvider.getObject()를 LogDemoController, LogDemoService에서 각각 한번씩 따로 호출해도 같은 HTTP 요청이면 같은 스프링 빈이 반환된다.

스코프와 프록시

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyLogger {
  • 여기가 핵심이다. proxyMode = ScopedProxyMode.TARGET_CLASS)를 추가한다.
  • 적용대상이 클래스면 TARGET_CLASS, 인터페이스라면 INTERFACES를선택
  • 이렇게 하면 MyLogger의 가짜 프록시 클래스를 만들어두고 HTTP request와 상관없이 가짜 프록시 클래스를 다른 빈에 미리 주입 해 둘수있다.

LogDemoController

@Controller
@RequiredArgsConstructor
public class LogDemoController {

    private final LogDemoService logDemoService;
    private final MyLogger myLogger;

    @RequestMapping("log-demo")
    @ResponseBody
    public String logDemo(HttpServletRequest request){
        String requestURL = request.getRequestURL().toString();
        System.out.println("myLogger = " + myLogger.getClass());
        myLogger.setRequestURL(requestURL);
        myLogger.log("controller test");
        logDemoService.logic("testId");
        return "Ok";
    }
}

LogDemoService

@Service
@RequiredArgsConstructor
public class LogDemoService {

    private final MyLogger myLogger;
    public void logic(String id) {
        myLogger.log("service id = " + id);
    }
}

결과

myLogger = class hello.core.common.MyLogger$$EnhancerBySpringCGLIB$$d9406574
[94e7cfeb-3a75-489b-83a3-bc57914371c0] request scope bean create : hello.core.common.MyLogger@6baea9cf
[94e7cfeb-3a75-489b-83a3-bc57914371c0][http://localhost:8080/log-demo] controller test
[94e7cfeb-3a75-489b-83a3-bc57914371c0][http://localhost:8080/log-demo] service id = testId
[94e7cfeb-3a75-489b-83a3-bc57914371c0] request scope bean close : hello.core.common.MyLogger@6baea9cf

 

CGLIB이라는 라이브러리로 내클래스를 상속 받은 가짜 프록시 객체를 만들어서 주입한다.

  • @Scope의 proxyMode = ScopedProxyMode.TARGET_CLASS)를 설정하면 스프링 컨테이너는 CGLIB라는 바이트코드를 조작하는 라이브러리를 사용해서 MyLogger를 상속받은 가짜 프록시 객체를 생성한다.
  • 결과를 확인해보면 등록한 순수한 MyLogger 클래스가 아니라 MyLogger$$EnhancerBySpringCGLIB$$이라는 클래스로 만들어진 객체가 대신 등록된 것을 확인 할 수 있다.
  • 그리고 스프링 컨테이너에 myLogger라는 이름으로 진짜 대신에 이 가짜 프록시 객체를 등록한다.
  • ac.getBean(MyLogger.class)로 조회해도 프록시 객체가 조회되는 것을 확인 할 수 있다.
  • 그래서 의존관계 주입도 이 가짜 프록시 객체가 주입된다.

가짜 프록시 객체는 요청이 오면 그떄 내부에서 진짜 빈을 요청하는 위임 로직이 들어있다.

  • 클라이언트가 myLogger.logic()을 호출하면 사실은 가짜 프록시 객체의 메서드를 호출한 것이다.
  • 가짜 프록시 객체는 request스코프의 진짜 myLogger.logic()을 호출한다.
  • 가짜 프록시 객체는 원본 클래스를 상속 받아서 만들어졌기 때문에 이 객체를 사용하는 클라이언트 입장에서는 사실 원본인지 아닌지 모르게 동일하게 사용할 수 있다.(다형성)

동작정리

  • CGLIB라는 라이브러리로 내 클래스를 상속받은 가짜 프록시 객체를 만들어서 주입한다.
  • 이 가짜 프록시 객체는 실제 요청이 오면 그때 내부에서 실제 빈을 요청하는 위임 로직이 들어있다.
  • 가짜 프록시 객체는 실제 request scope와는 관꼐가 없다. 내부에는 단순한 위임 로직만 있고, 싱글톤 처럼 동작한다.

특정정리

  • 프록시 객체 덕분에 클라이언트는 마치 싱글톤 빈을 사용하듯이 편리하게 request scope를 사용 할 수 있다.
  • 사실 Provider를 사용하든, 프록시를 사용하든 핵심 아이디어는 진짜 객체 조회를 꼭 필요한 시점까지 지연처리 한다는 점이다.
  • 단지 어노테이션 설정 변경만으로 우너본 객체를 프록시 객체로 대체 할 수 있다. 이것이 바로 다형성과 DI 컨테이너가 가진 가장 큰 강점이다.
  • 꼭 웹 스코프가 아니어도 프록시는 사용 할 수 있다.

주의점

  • 마치 싱글톤을 사용하는 것 같지만 다르게 동작하기 때문에 격국 주의해서 사용해야한다.
  • 이런 특별한 scope는 꼭 필요한 곳에만 최소화해서 사용하자, 무분별하게 사용하면 유지보수가 어렵다.

 

 

강의출처 : 스프링 핵심 원리 - 기본편 - 인프런 | 강의 (inflearn.com)

스프링 빈은 객체를 생성하고, 의존관계 주입이 다 끝난 다음에야 필요한 데이터를 사용 할 수 있는 준비가 완료된다.

따라서 초기화 작업은 의존관계 주입이 모두 완료되고 난 다음에 호출해야한다.

스프링은 의존관계 주입이 완료되면 스프링 빈에게 콜백 메서드를 통해 초기화 시점을 알려주는 다양한 기능을 제공한다.

또한, 스프링은 스프링 컨테이너가 종료되기 직전에 소멸 콜백을 준다.

스프링 빈의 이벤트 라이프 사이클

스프링 컨테이너 생성 → 스프링 빈 생성 → 의존관계 주입 → 초기화 콜백 → 사용 → 소멸전 콜백 → 스프링 종료

 

초기화 콜백 : 빈이 생성되고, 빈의 의존관계 주입이 완료된 후 호출

소멸전 콜백 : 빈이 소멸되기 직전에 호출

 

※ 객체의 생성과 초기화를 분리하자.

생성자는 필수 정보(파라미터)를 받고, 메모리을 할당해서 객체를 생성하는 책임을 가진다. 반면에 초기화는 이렇게 생성된 값들을 활용해서 외부 커넥션을 연결하는 등 무거운 동작을 수행한다.

따라서 생성자 안에서 무거운 초기화 작업을 함께하는 것 보다는 객체를 생성하는 부분과 초기화하는 부분을 명확하게 나누는것이 유지보수 관전에서 좋다. 

스프링은 크게 3가지 방법으로 빈 생명주기 콜백을 지원

  • 인터페이스(InitializingBean, DisposableBean)
  • 설정 정보에 초기화 메서드 ,종료 메서드 지정
  • @PostConstruct, @PreDestory 어노테이션 지원

인터페이스(InitializingBean, DisposableBean)

public class NetworkClient implements InitializingBean, DisposableBean {

    private String url;

    public NetworkClient(){
        System.out.println("생성자 url = " + url);

    }

    public void setUrl(String url) {
        this.url = url;
    }

    //서비스 시작시 호출
    public void connect(){
        System.out.println("connect =" + url);
    }

    public void call(String message) {
        System.out.println("call = " + url + ", message =" + message);
    }
    //서비스 종료시 호출
    public void disconnect() {
        System.out.println("close = " + url);
    }

    @Override
    public void destroy() throws Exception {
        connect();
        call("초기화 연결");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        disconnect();
    }
}

Test

public class BeanLifeCycleTest {

    @Test
    public void lifeCycleTest(){
        ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        NetworkClient networkClient = ac.getBean(NetworkClient.class);
        ac.close();

    }

    @Configuration
    static class LifeCycleConfig {

        @Bean
        public NetworkClient networkClient(){
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://hello-spring.dev");
            return networkClient;
        }
    }
}

결과

17:38:32.650 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@52e6fdee
17:38:32.729 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
17:38:33.233 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
17:38:33.238 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
17:38:33.240 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
17:38:33.243 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
17:38:33.266 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beanLifeCycleTest.LifeCycleConfig'
17:38:33.273 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'networkClient'
생성자 url = null
close = http://hello-spring.dev
17:38:33.417 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@52e6fdee, started on Tue Mar 28 17:38:32 KST 2023
connect =http://hello-spring.dev
call = http://hello-spring.dev, message =초기화 연결

 

스프링 컨테이너 생성 → 스프링 빈 생성 → 의존관계 주입이 끝난 시점에 초기화콜백  소멸 전 콜백

 

초기화,소멸 인터페이스 단점

  • 이 인터페이스는 스프링 전용 인터페이스이다. 해당 코드가 스프링 전용 인터페이스에 의존한다.
  • 초기화, 소멸 메서드의 이름을 변경 할 수 있다.
  • 내가 코드를 고칠수 없는 외부 라이브러리에 적용 할 수 없다.

설정 정보에 초기화 메서드 ,종료 메서드 지정

public class NetworkClient{

    private String url;

    public NetworkClient(){
        System.out.println("생성자 url = " + url);

    }

    public void setUrl(String url) {
        this.url = url;
    }

    //서비스 시작시 호출
    public void connect(){
        System.out.println("connect =" + url);
    }

    public void call(String message) {
        System.out.println("call = " + url + ", message =" + message);
    }
    //서비스 종료시 호출
    public void disconnect() {
        System.out.println("close = " + url);
    }


    public void init() {
        connect();
        call("초기화 연결");
    }

    public void close() {
        disconnect();
    }
}

Test

public class BeanLifeCycleTest {

    @Test
    public void lifeCycleTest(){
        ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        NetworkClient networkClient = ac.getBean(NetworkClient.class);
        ac.close();

    }

    @Configuration
    static class LifeCycleConfig {

        @Bean(initMethod = "init", destroyMethod = "close")
        public NetworkClient networkClient(){
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://hello-spring.dev");
            return networkClient;
        }
    }
}

설정 정보 사용 특징

  • 메서드 이름을 자유롭게 줄 수 있다.
  • 스프링 빈이 스프링 코드에 의존하지 않는다.
  • 코드가 아니라 설정 정보를 사용하기 때문에 코드를 고칠 수 없는 외부 라이브러리에도 초기화, 종료 메서드를 적용 할 수 있다.

종료 메서드 추론

  • @Bean의 'destoryMethod' 속성에는 아주 특별한 기능이 있다.
  • 라이브러리는 대부분 'close', 'shutdown'이라는 이름의 종료 메서드를 사용한다.
  • @Bean의 'destoryMehtod' 는 기본 값이 (inferred ) (추론)으로 등록되어있다.
  • 추론 기능은 'close', 'shutdown' 라는 이름의 메서드를 자동으로 호출해준다. 이름 그대로 종료 메서드를 추론해서 호출한다.
  • 따라서 직접 스프링 빈으로 등록하면 종료 메서드는 따로 적어주지 않아도 잘 동작한다.
  • 추론기능을 사용하기 싫으면 destoryMethod ="" 공백을 지정하면된다.

 

@PostConstruct, @PreDestory 어노테이션 지원

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class NetworkClient{

    private String url;

    public NetworkClient(){
        System.out.println("생성자 url = " + url);

    }

    public void setUrl(String url) {
        this.url = url;
    }

    //서비스 시작시 호출
    public void connect(){
        System.out.println("connect =" + url);
    }

    public void call(String message) {
        System.out.println("call = " + url + ", message =" + message);
    }
    //서비스 종료시 호출
    public void disconnect() {
        System.out.println("close = " + url);
    }


    @PostConstruct
    public void init() {
        connect();
        call("초기화 연결");
    }

    @PreDestroy
    public void close() {
        disconnect();
    }
}

Test

public class BeanLifeCycleTest {

    @Test
    public void lifeCycleTest(){
        ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        NetworkClient networkClient = ac.getBean(NetworkClient.class);
        ac.close();

    }

    @Configuration
    static class LifeCycleConfig {

        @Bean
        public NetworkClient networkClient(){
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://hello-spring.dev");
            return networkClient;
        }
    }
}

@PostConstruct, @PreDestory 어노테이션 특징

  • 최신 스프링에서 가장 권장하는 방법이다.
  • 어노테이션 하나만 붙이면 되기때문에 편리하다.
  • 단점으로 외부 라이브러리에는 적용하지 못하는 것이다. 외부 라이브러리를 초기화, 종료 해야한다면 @Bean의 기능을 사용하자.

 

강의출처 : 스프링 핵심 원리 - 기본편 - 인프런 | 강의 (inflearn.com)

 

생성정보를 기반으로 애플리케이션을 구성하는 부분과 실제 동작하는 부분을 명확하게 나누는 것이 이상적이지만,. 개발자 입장에서 스프링 빈을 하나 등록할때 @Component 만 넣어주면 끝나는 일을 @Configration 설정 정보에 가서 Bean을 적고 객체를 생성하고 주입할 대상을 일일이 적어주는 과정은 상당히 번거롭다.

 

애플리케이션은 크게 업무로직과 기술지원로직으로 나눌수 있다.

  • 업무 로직 빈 : 웹을 지원하는 컨트롤러, 핵심 비즈니스 로직이 있는 서비스, 데이터 계층의 로직을 처리하는 리포지토리 등이 모두 업무로직이다. 보통 비즈니스 요구사항을 개발할때 추가되거나 변경된다.
    • 업무로직은 숫자도 매우 많고, 한번 개발해야 하면 컨트롤러, 서비스, 리포지토리 처럼 어느정도 유사한 패턴이 있다. 이런 경우 자동기능을 적극 사용하는것이 좋다. 보통 문제가 발생해도 어떤곳에서 문제가 발생했는지 명확하게 파악하기 쉽다.
  • 기술 지원 빈 : 기술적인 문제나 공통 관심사(AOP)를 처리할때 주로 사용된다. 데이터베이스 연결이나, 공통 로그 처리처럼 업무 로직을 지원하기 위한 하부 기술이나 공통 기술들이다.
    • 기술지원로직은 업무로직과 비교해서 그 수가 매우 적고, 보통 애플리케이션 전반에 걸쳐서 광범위하게 영향을 미친다. 그리고 업무 로직은 문제가 발생했을때 어디가 문제인지 명확하게 잘 들어나지만, 기술지원로직은 적용이 잘되고 있는지 아닌지 조차 파악하기 어려운경우가 많다. 그래서 이런 기술지원 로직들은 가급적 수동 빈 등록을 사용해서 명확하게 들어내는 것이 좋다.

※ 애플리케이션에 광범위하게 영향을 미치는 기술 지원 객체는 수동 빈으로 등록해서 설정 정보에 바로 나타나게 하는것이 유지보수하기 좋다.

 

비즈니스 로직중에서 다형성을 활용할때

DiscountPolicy와 같이 다형성을 활용할때 여기에 어떤빈이 주입될지 쉽게파악하기 힘들다.

자동등록을 사용하고 있을때는 여러코드를 찾아봐야한다.

이런경우 수동빈으로 등록하거나 또는 자동으로하면 특정패키지에 같이 묶어 두는게 좋다.

 

강의출처 : 스프링 핵심 원리 - 기본편 - 인프런 | 강의 (inflearn.com)

서브쿼리는 하나의 SQL문 내에 또 하나의 SQL문을 말한다.

서브쿼리는 SELECT, FROM, WHERE 절에서 사용할 수 있다.

 

서브쿼리 종류는 대표적으로 단일 행 서브쿼리, 다중 행 서브쿼리가 있다.

 

 

 

강의출처 : https://www.inflearn.com/course/SQL-%EC%9D%B8%EC%A0%9D%EC%85%98-%EA%B3%B5%EA%B2%A9-%EA%B8%B0%EB%B3%B8-%EB%AC%B8%EB%B2%95#

+ Recent posts