Custom Annotation in Spring with BeanPostProcessor

2020-06-23 08:06发布

问题:

We are trying to create a Custom Annotation for our rest api in Spring. I am new to creating custom annotation, I have given the code snippet below

Spring Boot App --

@SpringBootApplication
@ComponentScan(basePackageClasses = {ServiceController.class, CustomAnnotatorProcessor.class})
public class ServiceApp {
    public static void main(String[] args) {            
        SpringApplication.run(ServiceApp.class, args);
    }
}

RestController --

@RestController
public class ServiceController {

    @RequestMapping(method = RequestMethod.GET, value="/service/v1/version")
    @ApiResponses(value = { 
            @ApiResponse(code = 200, message = "Success", response = String.class),
            @ApiResponse(code = 401, message = "Unauthorized"),
            @ApiResponse(code = 403, message = "Forbidden"),
            @ApiResponse(code = 404, message = "Not Found"),
            @ApiResponse(code = 500, message = "Failure")}) 
    @CustomAnnotation()
    public String getVersion() {
        return "success";
    }
}

Custom Annotation --

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface CustomAnnotation {

}

Annotation Processor --

@Component
public class CustomAnnotatorProcessor implements BeanPostProcessor {    

private ConfigurableListableBeanFactory configurableBeanFactory;

@Autowired
public CustomAnnotatorProcessor(ConfigurableListableBeanFactory beanFactory) {
    this.configurableBeanFactory = beanFactory;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    return bean;
}

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    MethodCallback methodCallback = new CustomAnnotationMethodCallback(configurableBeanFactory, bean);
    ReflectionUtils.doWithMethods(bean.getClass(), methodCallback);
    return bean;
}

Method Callback --

public class CustomAnnotationMethodCallback implements MethodCallback{
    @Override
    public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
        if (method.isAnnotationPresent(CustomAnnotation.class)) {
            System.out.println("doWith is getting called for CustomAnnotationMethodCallback");
            ReflectionUtils.makeAccessible(method);     
            //DO VALIDATION WHETHER A SPECIFIC HEADER IS PRESENT IN THE GIVEN REQUEST
            return;
        }       
    }

}   

I am trying to process the custom annotation in a class which implements BeanPostProcessor but I have an issue

Issue_1: The callback is getting called once but I am not able apply the validation for every request that is coming to the /service/v1/version API. I need to validate on every request, is our design / approach correct if so how to solve this problem, if not please suggest a different approach

Issue_2: If I need to pass the complete request object (alone with the header) to my @customAnnotation, how should I do that?

Please let me know if you need further details

Thanks

回答1:

To process the custom annotation @validateAuthentication, we created Intercepter class extending HandlerInterceptorAdapter.

We implementing our validation of the request header in preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) method.



回答2:

Issue_1: The callback is getting called once but I am not able apply the validation for every request that is coming to the /service/v1/version API. I need to validate on every request, is our design / approach correct if so how to solve this problem, if not please suggest a different approach

Issue_2: If I need to pass the complete request object (alone with the header) to my @customAnnotation, how should I do that?

I think you should use spring AOP or Interceptor other than Annotation.