[Spring] 빈 스코프

Seongho·2023년 6월 7일
0

Spring

목록 보기
12/13

빈 스코프

빈 스코프란 스프링 DI 컨테이너에서 빈이 생성되고 소멸되기까지 빈이 존재하는 범위이다.

  • 싱글톤 스코프
  • 프로토타입 스코프
  • request 스코프
  • session 스코프
  • application 스코프

프로토타입 스코프

프로토타입 빈 스코프는 조회할 때마다 스프링 DI 컨테이너에서 새로운 빈 인스턴스를 만들어 반환한다.

프로토타입 빈을 조회하면 컨테이너는 빈 인스턴스를 생성하고 의존관계를 주입한다. 그 후, 빈을 클라이언트에 반환하고 더이상 관리하지 않는다.
스프링 컨테이너는 프로토타입 빈을 생성하고 의존관계를 주입하고 초기화 하는 단계까지만 처리한다. 그 후, 빈을 관리하는 책임은 클라이언트에 있다.

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

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

위와 같이 싱글톤 빈에 프로토타입 빈을 의존관계를 주입하여 사용할 때, 개발자의 의도와 다르게 동작할 수 있다.

싱글톤 빈인 ClientBean에 PrototypeBean을 의존관계 주입하였다.

그 후, 클라이언트 A에서 ClientBean의 logic()을 호출하여 PrototypeBean의 count를 1로 증가시킨 후,

그 후, 클라이언트 B에서 ClientBean의 logic()을 호출하여 PrototypeBean의 count를 2로 증가시킨다.
그러나, count를 조작할 때, PrototypeBean을 사용한 개발자의 의도는, 모든 클라이언트에게 각각 PrototypeBean을 반환하고 각각의 count 변수를 조작하게 하려는 것이었을 것이다.
따라서, 공유되지 않아야 할 자원이 공유되는 일이 발생한다.

해결 -> ObjectProvider, JSR330 Provider

@Autowired
private ObjectProvider<PrototypeBean> prototypeBeanProvider;
//
public int logic() {
   PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
   prototypeBean.addCount();
   int count = prototypeBean.getCount();
   return count;
}
  • prototypeBeanProvider.getObject()를 통해 새로운 프로토타입 빈이 생성된다.
  • 프로토타입 빈을 대신 조회하는 대리자라고 생각.
  • ObjectProvider는 스프링이 제공하는 기능, JSR330 Provider는 자바 표준 기능이다.
    코드를 스프링 컨테이너가 아닌 다른 컨테이너에서도 사용해야 한다면 자바 표준을 쓰고, 그게 아니면 스프링에서 제공하는 기능을 사용하면 된다.
profile
Record What I Learned

0개의 댓글