Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

Kwon's Study Blog !

[Spring] 스프링 핵심원리 기본편 - 빈 스코프 본문

Spring

[Spring] 스프링 핵심원리 기본편 - 빈 스코프

순샤인 2022. 4. 16. 23:20

이글은 스프링핵심원리-기본편-인프런 강의를 학습 후 
나중에 다시 복습하기 위해 정리한 글입니다.
문제시 비공개로 처리하겠습니다. 
 

스프링 핵심 원리 - 기본편 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., - 강의 소개 | 인프런...

www.inflearn.com

 

목차

  1. 빈 스코프 란?
  2. 프로토타입 스코프
  3. 프로토타입 스코프 문제점
  4. 문제점 Provider 로 해결
  5. 웹 스코프
  6. 스코프와 Provider
  7. 스코프와 프록시

1. 빈 스코프 란 ?

지금까지는 스프링 빈이 스프링 컨테이너의 생성 - 종료될 때 까지 유지된다고 학습했다.

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

스코프는 말 그대로 빈이 존재할 수 있는 범위를 말한다.

스프링이 지원하는 스코프

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

ex) 빈 스코프는 다음과 같이 지정할 수 있다.

  • 컴포넌트 스캔 자동 등록
@Scope("prototype")
@Component
public class HelloBean {}
  • 수동 등록
@Scope("prototype")
@Bean
PrototypeBean HelloBean() {
 return new HelloBean();
}

2. 프로토타입 스코프

먼저 싱글톤 스코프를 살펴보자.

@Scope(”singleton”)

  • 싱글톤 빈 요청

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

테스트

public class SingletonTest {

    @Test
    public void singletonBeanFind(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SingletonBean.class);

        SingletonBean singletonBean1 = ac.getBean(SingletonBean.class);
        SingletonBean singletonBean2 = ac.getBean(SingletonBean.class);

        System.out.println("singletonBean1 = " + singletonBean1);
        System.out.println("singletonBean2 = " + singletonBean2);

        Assertions.assertThat(singletonBean1).isSameAs(singletonBean2);

        ac.close();
    }

    @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@35645047
singletonBean2 = hello.core.scope.SingletonTest$SingletonBean@35645047
18:57:06.912 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6d4e5011, started on Sun Jan 16 18:57:06 KST 2022
SingletonBean.destroy

@Scope(”prototype”)

프로토타입 스코프를 스프링 컨테이너에 조회하면 스프링 컨테이너는 항상 새로운 인스턴스

반환한다.

  • 프로토타입 빈 요청

  1. 프로토타입 스코프의 빈을 스프링 컨테이너에 요청한다.
  2. 스프링 컨테이너는 이 시점에 프로토타입 빈을 생성하고, 필요한 의존관계를 주입한다.
  3. 스프링 컨테이너는 생성한 프로토타입 빈을 클라이언트에 반환한다.
  4. 이후에 스프링 컨테이너에 같은 요청이 오면 항상 새로운 프로토타입 빈을 생성해서 반환한다.

핵심 :

스프링 컨테이너는 프로토타입 빈을 생성하고, 의존관계 주입, 초기화까지만 처리한다는 것이다.

 

클라이언트에 빈을 반환하고, 이후 스프링 컨테이너는 생성된 프로토타입 빈을 관리하지 않는다.

 

프로토타입 빈을 관리할 책임은 프로토타입 빈을 받은 클라이언트에 있다.

그래서 @PreDestroy 같은 종료 메서드가 호출되지 않는다.

 

테스트

public class PrototypeTest {

    @Test
    public void prototypeBeanFind(){
        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@35645047
prototypeBean2 = hello.core.scope.PrototypeTest$PrototypeBean@6f44a157
19:24:46.942 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6d4e5011, started on Sun Jan 16 19:24:46 KST 2022

싱글톤 빈은 스프링 컨테이너 생성 시점에 초기화 메서드가 실행 되지만,

프로토타입 빈은 스프링 컨테이너에서 빈을 조회할 때 생성되고 초기화 메서드도 실행된다.

 

프로토타입 빈을 2번 조회했으므로 완전히 다른 스프링 빈이 생성되고, 초기화도 2번 실행된 것을 볼 수있다.

 

싱글톤 빈은 스프링 컨테이너가 관리하기 때문에 스프링 컨테이너가 종료될 때 빈의 종료 메서드가 실행되지만,

프로토타입 빈은 스프링 컨테이너가 생성과 의존관계 주입 그리고 초기화 까지만 관여하고, 더는 관리하지 않는다.

따라서 프로토타입 빈은 스프링 컨테이너가 종료될 때 @PreDestroy 같은 종료 메서드가 전혀 실행되지 않는다.

클라이언트가 직접 호출해줘야 한다. (prototypeBean1.destroy() )

public class PrototypeTest {

    @Test
    public void prototypeBeanFind(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        Assertions.assertThat(prototypeBean1).isNotSameAs(prototypeBean2);
        prototypeBean1.destroy();
        prototypeBean2.destroy();
        ac.close();

    }

프로토타입 빈의 특징 정리

  • 스프링 컨테이너에 요청할 때 마다 새로 생성된다.
  • 스프링 컨테이너는 프로토타입 빈의 생성의존관계 주입 그리고 초기화까지만 관여한다.
  • 종료 메서드가 호출되지 않는다. → 프로토타입 빈은 프로토타입 빈을 조회한 클라이언트가 관리해야 한다. → (종료 메서드에 대한 호출도 클라이언트가 직접 해야한다.)

3. 프로토타입 스코프 문제점

싱글톤 빈과 함께 사용 시 문제점(주의점)

스프링 컨테이너에 프로토타입 스코프의 빈을 요청하면 항상 새로운 인스턴스를 생성해서 반환한다.

하지만 싱글톤 빈과 함께 사용할 때의도한 대로 잘 동작하지 않으므로 주의해야 한다.

 

먼저 스프링 컨테이너에 프로토타입 빈을 직접 요청하는 예제를 보자.

  • 스프링 컨테이너에 프로토타입 빈 직접 요청1

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

  1. 클라이언트B는 스프링 컨테이너에 프로토타입 빈을 요청한다.
  2. 스프링 컨테이너는 프로토타입 빈을 새로 생성해서 반환(x02)한다.
  3. 해당 빈의 count 필드 값은 0이다.
  4. 클라이언트는 조회한 프로토타입 빈에 addCount() 를 호출하면서 count 필드를 +1 한다.
  5. (x02)의 count값은 1이다.

테스트

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 = 0;

        public void addCount(){
            count++;
        }

        public int getCount(){
            return count;
        }

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

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

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

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

(싱글톤 빈 ← 프로토타입 빈)

  • 싱글톤과 프로토타입 빈 사용1

  1. clientBean 은 싱글톤이므로, 보통 스프링 컨테이너 생성 시점에 함께 생성되고, 의존관계 주입도 발생한다.
  2. 주입 시점에 스프링 컨테이너에 프로토타입 빈을 요청한다.
  3. 스프링 컨테이너는 프로토타입 빈을 생성해서 clientBean 에 반환한다.
  4. 프로토타입 빈의 count 값은 0 이다.
  5. clientBean 은 프로토타입 빈을 내부 필드에 보관한다. (정확히는 참조값을 보관한다.)
  • 싱글톤에서 프로토타입 빈 사용2

  1. 클라이언트 A는 clientBean 을 스프링 컨테이너에 요청해서 받는다.
  2. 클라이언트 A는 clientBean.logic() 을 호출한다.
  3. prototypeBean의 addCount() 를 호출해서 프로토타입 빈의 count를 증가한다. count값이 1이 된다.
  • 싱글톤에서 프로토타입 빈 사용3

  1. 클라이언트 B는 clientBean 을 스프링 컨테이너에 요청해서 받는다.
  2. 클라이언트 B는 clientBean.logic() 을 호출한다.
  3. prototypeBean의 addCount() 를 호출해서 프로토타입 빈의 count를 증가한다. count값이 2가 된다.

테스트

public class SingletonWithPrototypeTest1 {

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

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

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

    static class ClientBean{

        private final PrototypeBean prototypeBean;

        @Autowired
        public ClientBean(PrototypeBean prototypeBean) {
            this.prototypeBean = prototypeBean;
        }

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

    @Scope("prototype")
    static class PrototypeBean{

        private int count = 0;

        public void addCount(){
            count++;
        }

        public int getCount(){
            return count;
        }

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

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

clientBean이 내부에 가지고 있는 프로토타입 빈은 이미 과거에 주입이 끝난 빈이다.

 

주입 시점에 스프링 컨테이너에 요청해서 프로토타입 빈이 새로 생성이 된 것이지,

사용 할 때마다 새로 생성되는 것이 아니다!

 

어쩌면 당연한 결과지만, 아마 원하는 것이 이런 것은 아닐 수도 있다.

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


4. 문제점 Provider로 해결

싱글톤 빈과 함께 사용 시 Provider로 문제 해결

싱글톤 빈과 프로토타입 빈을 함께 사용할 때,

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

1. 스프링 컨테이너에 요청

가장 간단한 방법은

싱글톤 빈이 프로토타입을 사용할 때 마다 스프링 컨테이너에 새로 요청하는 것이다.

public class SingletonWithPrototypeTest1 {

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

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

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

    static class ClientBean{

        // 스프링 컨테이너 자동 주입
        @Autowired 
        private ApplicationContext ac;

        public int logic(){
            PrototypeBean prototypeBean = ac.getBean(PrototypeBean.class);
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }

    @Scope("prototype")
    static class PrototypeBean{

        private int count = 0;

        public void addCount(){
            count++;
        }

        public int getCount(){
            return count;
        }

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

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

위 코드의 핵심은 여기다.

	static class ClientBean{
				
	private ApplicationContext ac;
	
	public int logic(){
		PrototypeBean prototypeBean = ac.getBean(PrototypeBean.class);
	}
}

ac.getBean() 을 통해서 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다.

 

위 코드는

의존관계를 외부에서 주입(DI) 받는게 아니라

내부에 스프링 컨테이너 빈을 아예 통째로 가져다가 사용하고 있다.

이처럼,

직접 필요한 의존관계를 찾는 것을 Dependency Lookup (DL) 의존관계 조회(탐색) 이라한다.

 

그런데 이렇게 스프링의 애플리케이션 컨텍스트 전체를 주입받게 되면,

스프링 컨테이너에 종속적인 코드가 되고 (스프링 → 다른 DI 컨테이너로 이동할 때 곤란해짐)

단위 테스트도 어려워진다.

 

지금 필요한 기능은 지정한 프로토타입 빈을 컨테이너에서 대신 찾아주는

딱! DL 정도의 기능만 제공하는 무언가가 있으면 된다.

2. ObjectFactory, ObjectProvider

지정한 빈을 컨테이너에서 대신 찾아주는 DL 서비스를 제공하는 것이 바로 ObjectProvider 이다.

참고 : 과거에는 ObjectFactory 가 있었는데 → 여기에 편의 기능을 추가해서 ObjectProvider 가 만들어졌다

static class ClientBean{

        @Autowired
        private ObjectProvider<PrototypeBean> prototypeBeanProvider;

        public int logic(){
            PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }
  • prototypeBeanProvider.getObject() 을 통해서 항상 새로운 프로토타입 빈이 생성된다.
  • ObjectProvidergetObject() 를 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다. (DL)
  • 스프링이 제공하는 기능을 사용하지만, 기능이 단순하므로 단위테스트를 만들거나 mock 코드를 만들기는 훨씬 쉬워진다.
  • ObjectProvider 는 지금 딱 필요한 DL 정도의 기능만 제공한다.

Provider가 이 경우(싱글톤 빈에서 프로토타입 빈을 의존하는 경우) 를 해결 할 순 있지만,

사실 핵심 컨셉스프링 컨테이너에 조회하는데 직접 조회하기 보단 대신 조회하는 대리자 느낌.

 

특징

  • ObjectFactory : 기능이 단순, 별도의 라이브러리 필요 없음, 스프링에 의존
  • ObjectProvider : ObjectFactory 상속, 옵션, 스트림 처리등 편의 기능이 많고, 별도의 라이브러리 필요 없음, 스프링에 의존

3. JSR-330 Provider

이 방법은 javax.inject.Provider 라는 JSR-330 자바 표준을 사용하는 방법이다.

 

이 방법을 사용하려면 javax.inject:javax.inject:1 라이브러리를 gradle에 추가해야 한다.

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter'
	implementation 'javax.inject:javax.inject:1'
}
static class ClientBean{

        @Autowired
        private Provider<PrototypeBean> provider;

        public int logic(){
            PrototypeBean prototypeBean = provider.get();
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }
  • provider.get()을 통해서 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다.
  • Provider의 get을 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다. (DL)
  • 자바 표준이고, 기능이 단순하므로 단위테스트를 만들거나 mock 코드를 만들기는 훨씬 쉬워진다.
  • Provider는 지금 딱 필요한 DL 정도의 기능만 제공한다.

특징

  • get() 메서드 하나로 기능이 매우 단순하다.
  • 별도의 라이브러리가 필요하다.
  • 자바 표준이므로 스프링이 아닌 다른 컨테이너에서도 사용할 수 있다.

정리

  • 프로토타입 빈은 사용할 때 마다 새로운 객체가 필요하면 사용하면 된다. → 그런데 사실, 실무에선 사용되는 일이 거의 없다.
  • ObjectProvider , JSR330 Provider 등은 프로토타입 뿐만 아니라 DL이 필요한 경우는 언제든지 사용할 수 있다.
  • 그 외 Provider가 필요한 경우
/*
retrieving multiple instances.
lazy or optional retrieval of an instance.
breaking circular dependencies.
abstracting scope so you can look up an instance in a smaller scope from an instance in a containing scope.
*/

ObjectProvider는 DL을 위한 편의 기능을 많이 제공해주고,

스프링 외에 별도의 의존관계 추가가 필요 없기 때문에 편리하다.

만약(정말 그럴일은 거의 없겠지만) 코드를 스프링이 아닌 다른 컨테이너에서도 사용할 수 있어야 한다면 JSR-330 Provider를 사용해야한다.

 

PrototypeBean prototypeBean = new PrototypeBean();Provider차이점

스프링 컨테이너에 있다.

Provider를 사용하면 스프링 컨테이너를 통해서 조회하기 때문에

필요한 의존관계 주입초기화 콜백의 도움을 받을 수 있다.

참고 : 스프링이 제공하는 메서드에 @Lookup 애노테이션을 사용하는 방법도 있지만, 이전 방법들로 충분하고, 고려해야할 내용도 많아서 생략.


5. 웹 스코프

웹 스코프

웹 스코프 특징

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

웹 스코프 종류

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

HTTP request 요청 당 각각 할당되는 request 스코프

하나의 request 요청에 대해 응답이 될 때 까지 종료되지 않으며,

같은 request요청이라면 Controller나 Service단 에서도 같은 인스턴스 객체를 사용한다.

request 스코프 예제 만들기

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

 

이 방법을 사용하려면 spring-boot-starter-web 라이브러리를 gradle에 추가해야 한다.

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter'
	implementation 'javax.inject:javax.inject:1'
	//web 라이브러리 추가
	implementation 'org.springframework.boot:spring-boot-starter-web'
}

hello.core.CoreApplication 의 main 메서드를 실행. → 웹 애플리케이션이 실행.

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.4)

2022-01-17 02:12:49.340  INFO 13928 --- [           main] hello.core.CoreApplication               : Starting CoreApplication using Java 11.0.11 on DESKTOP-M8JMIMM with PID 13928 (C:\Users\kwons\Desktop\study\git_project\spring_basic\core\out\production\classes started by kwons in C:\Users\kwons\Desktop\study\git_project\spring_basic\core)
2022-01-17 02:12:49.344  INFO 13928 --- [           main] hello.core.CoreApplication               : No active profile set, falling back to default profiles: default
2022-01-17 02:12:50.906  INFO 13928 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-01-17 02:12:50.918  INFO 13928 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-01-17 02:12:50.918  INFO 13928 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.52]
2022-01-17 02:12:50.999  INFO 13928 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-01-17 02:12:50.999  INFO 13928 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1589 ms
call AppConfig.memberRepository
call AppConfig.memberService
call AppConfig.orderService
2022-01-17 02:12:51.406  INFO 13928 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-01-17 02:12:51.415  INFO 13928 --- [           main] hello.core.CoreApplication               : Started CoreApplication in 2.532 seconds (JVM running for 2.969)
2022-01-17 02:13:08.218  INFO 13928 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-17 02:13:08.219  INFO 13928 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-01-17 02:13:08.219  INFO 13928 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms

Process finished with exit code 130

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

참고 : 스프링 부트는 웹 라이브러리가 없으면 AnnotationConfigApplicationContext 을 기반으로 애플리케이션을 구동한다. 있으면 웹과 관련된 추가 설정과 환경들이 필요하므로 AnnotationConfigServletWebServerApplicationContext 를 기반으로 애플리케이션을 구동한다.

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

//main/resources/application.propertie
server.port=9090

동시에 여러 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을 요청해서 남은 로그인지 확인하자.

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에 저장해둔다.
  • 컨트롤러에서 controller test라는 로그를 남긴다.
참고 : requestURL을 MyLogger에 저장하는 부분은 컨트롤러 보다는 공통 처리가 가능한 스프링 인터셉터서블릿 필터 같은 곳을 활용하는 것이 좋다. 스프링 웹에 익숙하다면 인터셉터를 사용해서 구현해보자.

LogDemoService

@Service
@RequiredArgsConstructor
public class LogDemoService {

    private final MyLogger myLogger;

    public void logic(String id){
        myLogger.log("service id = " + id);
    }
}
  • 비즈니스 로직이 있는 서비스 계층에서도 로그를 출력해보자.

request scope를 사용하지 않고 파라미터로 이 모든 정보를 서비스 계층에 넘긴다면,

파라미터가 많아서 지저분해진다. → MyLogger의 멤버변수로 해결

더 문제는 requestURL 같은 웹과 관련된 정보가 웹과 관련없는 서비스 계층까지 넘어가게 된다.

웹과 관련된 부분은 컨트롤러까지만 사용해야 한다.

서비스 계층은 웹 기술에 종속되지 않고, 가급적 순수하게 유지하는 것이 유지보수 관점에서 좋다.

 

실행 !!!

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;

읭 ???

스프링 애플리케이션을 실행 시키면 오류가 발생한다.

 

why ?

Controller 빈이 생성되는 시점에 myLogger 에 의존관계 주입이 되야 하는데

myLogger는 스코프가 request 이기 때문에 아직 생성이 안되어 있다. ;;

다른 싱글톤 빈이라면 그 빈을 생성시키고 주입 시키겠지만

request 스코프인 빈은 실제 고객 요청이 와야 생성할 수 있다. !!!

 

이 문제를 어떻게 해결할까 ?

해결 방법은 MyLogger 빈을 지연 생성 시키는 것에 있다.

Provider를 사용하면 이 문제를 간단히 해결할 수 있다.


6. 스코프와 Provider

ObjectProvider 사용

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);
    }

}

는 바뀐게 없다.

 

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);
    }
}

잘 실행이 되며,

웹 브라우저에 http://localhost:8080/log-demo 를 입력하자.

[ad995794-4e0e-4de8-a453-1e75ad55f207]request scope bean createhello.core.common.MyLogger@3969896
[ad995794-4e0e-4de8-a453-1e75ad55f207][http://localhost:8080/log-demo]controller test
[ad995794-4e0e-4de8-a453-1e75ad55f207][http://localhost:8080/log-demo]service id = testId
[ad995794-4e0e-4de8-a453-1e75ad55f207]request scope bean closehello.core.common.MyLogger@3969896

[18a838af-075f-4423-9ee5-94b197aedd10]request scope bean createhello.core.common.MyLogger@333141f7
[18a838af-075f-4423-9ee5-94b197aedd10][http://localhost:8080/log-demo]controller test
[18a838af-075f-4423-9ee5-94b197aedd10][http://localhost:8080/log-demo]service id = testId
[18a838af-075f-4423-9ee5-94b197aedd10]request scope bean closehello.core.common.MyLogger@333141f7

[b3112fb4-355f-44aa-9b9c-4f17af230e64]request scope bean createhello.core.common.MyLogger@35eacf82
[b3112fb4-355f-44aa-9b9c-4f17af230e64][http://localhost:8080/log-demo]controller test
[b3112fb4-355f-44aa-9b9c-4f17af230e64][http://localhost:8080/log-demo]service id = testId
[b3112fb4-355f-44aa-9b9c-4f17af230e64]request scope bean closehello.core.common.MyLogger@35eacf82

ObjectProvider덕분에 myLoggerProvider.getObject() 를 호출하는 시점까지 request scope 빈

생성을 지연할 수 있다.

myLoggerProvider.getObject()를 호출하시는 시점에는 HTTP 요청이 진행중이므로

request scope 빈의 생성이 정상 처리된다.

 

myLoggerProvider.getObject()LogDemoController, LogDemoService에서 각각 한번씩 따로

호출해도 같은 HTTP 요청이면 같은 스프링 빈이 반환된다!

(하나의 요청에서 벌어지는 일들 이기 때문에 )


7. 스코프와 프록시

proxyMode

MyLogger

@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를 확인해보자

System.out.println("myLogger = "+myLogger.getClass());

//myLogger = class hello.core.common.MyLogger$$EnhancerBySpringCGLIB$$e482b23e

@Configuration 처럼 바이트 코드 조작이 일어난 것을 알 수 있다.

 

일단, 이제부터 글이 좀 많고 어려울 수 있으니 집중해서 보자.

 

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

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

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

동작 정리

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

특징 정리

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

주의점

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

 

위의 빈 스코프 - 4. 문제점 Provider로 해결 파트에서 (싱글톤 안에 프로토 타입 스코프)

예제를 Provider 에서 프록시모드로 한 번 바꿔보자.

public class SingletonWithPrototypeTest1 {

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

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

    }

    static class ClientBean{

        @Autowired
	    PrototypeBean protypeBean; // <- 가짜 프록시 객체 주입
        //private Provider<PrototypeBean> provider;
				

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

    @Scope(value="prototype",proxyMode = ScopedProxyMode.TARGET_CLASS)
    static class PrototypeBean{

        private int count = 0;

        public void addCount(){
            count++;
        }

        public int getCount(){
            return count;
        }

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

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

로직 부분에서

 1       public int logic(){
 2           //PrototypeBean prototypeBean = provider.get();
 3           prototypeBean.addCount(); 
 4           int count = prototypeBean.getCount();
 5           return count;
        }

3,4 번 라인에서 → 각각 새로운 프로토타입 빈이 생성이 된다.

스프링 컨테이너로 부터 생성이 되기에 초기화 메서드도 콜백된다.

 

prototypeBean 에 프록시 객체가 들어가 있다.

로직(addCount(), getCount())을 수행 하는 시점에

프록시 객체는 스프링 컨테이너에게 진짜 빈을 요청하고, 그 진짜 빈의 함수를 실행한다.

그런데 하필 요청 한 빈이 프로토타입 이기에 매번 새로운 빈이 생성이 되는 것이다.

(왜냐, 프로토타입 스콥은 스프링 컨테이너에서 요청 할 때 새로운 빈이 생성이 되기 때문이다.)