실제 다른 tomcat filter나 spring interceptor와 달리, 특정한 서비스에 대해서만
인터셉터 기능을 추가하고 싶을 때, 해당 기능을 사용할 수 있다.
가장 먼저, testService를 생성하도록 한다.
간단히, 해당 메서드가 호출되면 "testService String"을 출력해주도록 생성하였다.
package org.blog.test.service.impl; import org.blog.test.service.TestService; import org.springframework.stereotype.Service; @Service public class TestServiceImpl implements TestService { @Override public void testMethod() { System.out.println("testService String"); } }
다음으로 해당 service가 실행될 때, 앞뒤로 추가할 기능을 설정하는 interceptor를 아래와 같이 생성한다.
package org.blog.test.common; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.cglib.proxy.MethodProxy; import org.springframework.stereotype.Component; import java.lang.reflect.Method; @Component public class TestServiceInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("before method"); Object retVal = invocation.proceed(); System.out.println("after method"); return retVal; } }
마지막으로, 해당 서비스와 생성한 interceptor를 아래와 같이 연결시켜주면 끝~~!!
package org.blog.test.config; import org.blog.test.service.TestService; import org.springframework.aop.framework.ProxyFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration public class MethodInterceptorConfig { @Autowired private TestService testService; @Bean @Primary public ProxyFactoryBean testProxyFactoryBean() { ProxyFactoryBean testProxyFactoryBean = new ProxyFactoryBean(); testProxyFactoryBean.setTarget(testService); testProxyFactoryBean.setInterceptorNames("testServiceInterceptor"); return testProxyFactoryBean; } }
위와 같이 생성 후, 실행시키면 아래와 같이 실제 서비스 실행 이전과 이후에 설정한대로 동작하는 것을 확인할 수 있다.
- 출력 결과
before method testService String after method
전체 예제는 아래 링크에서 다운로드 받을 수 있다.
https://gitlab.com/shashaka/method-interceptor-project
댓글 없음 :
댓글 쓰기