spring mvc에서 서비스(@Service)의 메서드에 적용되어 있는 어노테이션을 가져오는 방법
조회수 2012회
안녕하세요.
public class DataSourceRoutingInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod method = (HandlerMethod) handler;
ReadOnly readOnly = method.getMethodAnnotation(ReadOnly.class);
readOnly = (readOnly == null) ? method.getBeanType().getAnnotation(ReadOnly.class) : readOnly;
// do something
return true;
}
}
위 코드는 컨트롤러의 메서드에 적용된 어노테이션을 가져오는 코드로 알고 있습니다. 그런데 서비스에 적용된 어노테이션은 어떻게 접근해야 하는지 감을 못잡겠네요.
@Service
public class ExampleService {
@Autowired
private ExampleDao exampleDao;
@ReadOnly
public SheetResponseObject getUserList(ExampleParam param) {
SheetResponseObject responseObject = new SheetResponseObject();
responseObject.setTotal(exampleDao.getUserListCount());
responseObject.setData(exampleDao.getUserList(param));
return responseObject;
}
}
바로 요 메서드에 @ReadOnly 어노테이션이 있나 없나 확인하고 싶어요. 스프링은 4.3 쓰고 있습니다.
1 답변
-
서비스 인스턴스를 사용할 때 검사하면됩니다.
Object service = ... ; // Service 인스턴스이고, ExampleService 인스턴스 일때, Method m = service.getClass().getMethod("getUserList",ExampleParam.class); // java.reflect.Method ReadOnly readOnly = m.getAnnotation(ReadOnly.class); ...
기본적으로 위와 같이 하면됩니다.
- http://blog.javaforge.net/post/76125490725/spring-aop-method-interceptor-annotation 여기 참고 했습니다. 답변 감사합니다. 편집요청빌런 2016.11.28 10:46
- AOP를 사용하는 경우는 가로채는 인터페이스 상에 method가 제공됩니다. MethodInvocation 인터페이스의 경우는 getMethod를 통해서 원래 호출하려고 했던 method 리플렉션을 얻을 수 있습니다. 해당 method 리플렉션에서 Annotation 정보를 획득하면 됩니다. 허대영(소프트웨어융합대학) 2016.11.28 12:25
댓글 입력