To get the annotation applied to the method of service (@Service) in spring mvc

Asked 2 years ago, Updated 2 years ago, 69 views

Hello.

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

I understand that the above code is the code to get the annotation applied to the controller's method. But I don't know how to approach the annotation applied to the service.

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

I want to check if this method has an @ReadOnly annotation or not. I'm using the spring 4.3.

spring java

2022-09-22 20:34

1 Answers

You can scan it when you use a service instance.

Object service = ... ; // This is the Service instance, and this is the ExampleService instance

Method m = service.getClass().getMethod("getUserList",ExampleParam.class);
// // java.reflect.Method

ReadOnly readOnly = m.getAnnotation(ReadOnly.class);

...

By default, you can do the same as above.


2022-09-22 20:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.