@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)아래 예시는 request 빈을 이용한 예시이다.
@Scope(value = "request")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 RequestBean {
private String uuid;
@PostConstruct
public void init(){
String uuid = UUID.randomUUID().toString();
System.out.println("[" + uuid+ "]" + " start");
}
@PreDestroy
public void destroy(){
System.out.println("[" + uuid+ "]" + " close");
}
public void logic(){
System.out.println(this);
}
}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class RequestController {
private final RequestService requestService;
public RequestController(RequestService requestService) {
this.requestService = requestService;
}
@RequestMapping("test")
@ResponseBody
public String test(){
requestService.logic();
return "OK";
}
}
import org.springframework.stereotype.Service;
@Service
public class RequestService {
private final RequestBean requestBean;
public RequestService(RequestBean requestBean) {
this.requestBean = requestBean;
}
public void logic(){
requestBean.logic();
}
}
실행결과 - 오류발생
Error creating bean with name 'requestBean':
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;
이 문제는 provider로 해결할 수 있다.
provider와 proxy는 모두 객체를 사용하기 전까지 다른 것으로 대체하고 실제 하용할 때 접근한다.(지연처리) 아래는 프록시로 해결한 모습이다.
Service 코드
- requestBean을 provider로 받아온다.
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestBean {
// 위와 동일
}
실행 결과
[88c79a86-7308-4bdd-a18f-78aae4ebbc32] start
test.core.request.RequestBean@7b02f558class test.core.request.RequestBean$$EnhancerBySpringCGLIB$$e024bbed
[null] close
출처
인프런 '스프링 핵심 원리 - 기본편' 강의