Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[20210305] Spring 인터셉터(Interceptor), @PostConstruct #58

Open
JuHyun419 opened this issue Mar 5, 2021 · 0 comments
Open

[20210305] Spring 인터셉터(Interceptor), @PostConstruct #58

JuHyun419 opened this issue Mar 5, 2021 · 0 comments
Labels

Comments

@JuHyun419
Copy link
Owner

JuHyun419 commented Mar 5, 2021

Filter(필터) vs Interceptor(인터셉터)

  • 필터는 DispatcherServlet이 실행되기 전에 수행(Spring 영역 X, Servlet)
  • 필터는 동일한 웹 애플리케이션 내에서 접근 가능
  • 인터셉터는 DispatcherServlet이 실행된 후 수행(Spring 영역)
  • 인터셉터는 특정 URI 요청 시, Controller을 타기 전에 가로챈다.
  • 인터셉터는 스프링의 모든 객체(Bean)에 접근 가능
  • HandlerInterceptor 인터페이스 및 HandlerInterceptorAdapter 추상 클래스를 상속받는 방법이 있음
  • 보통 추상 클래스를 상속받아 아래 메서드를 구현
  • preHandle(): Controller 요청 전 수행
  • postHandle(): Controller 요청 후 수행
  • afterCompletion(): View까지 처리가 끝난 후 수행
public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor {

	/**
	 * This implementation always returns {@code true}.
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
		return true;
	}

	/**
	 * This implementation is empty.
	 */
	public void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
	}

	/**
	 * This implementation is empty.
	 */
	public void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

@PostConstruct

  • DI(의존성 주입)은 생성자를 호출하는 시점에는 이루어지지 않기에 주입받은 의존성에 대한 작업이 필요할 때 사용하는 어노테이션
  • 또한 @PostConstruct 가 적용된 메소드는 Bean LifeCycle 안에서 단 한 번만 수행될 것이 보장되기 때문에 프록시 사용 등의 이유로 프레임워크 내에서 생성자의 호출이 여러번 발생할 경우 고려해 볼 수 있음
  • 디버깅모드로 확인해본 결과, Bean이 생성되기 전 해당 어노테이션의 메서드가 호출된다.
class Foo {

    @Autowired
    Bar bar;
    
    Foo() {
    	System.out.println(bar); // null
    	System.out.println("bar dose not injected");
    }
    
    @PostConstruct
    public void barInit() {
    	System.out.println(bar); // package.Bar@...
    	System.out.println("bar is injected.");
    }
}

References

https://velog.io/@hellozin/%EC%8A%A4%ED%94%84%EB%A7%81-%EB%B9%88%EC%9D%98-%EC%83%9D%EC%84%B1%EC%9E%90-afterPropertiesSet-PostConstruct

@JuHyun419 JuHyun419 changed the title [20210305] Spring 인터셉터(Interceptor) [20210305] Spring 인터셉터(Interceptor), @PostConstruct Mar 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant