0

I have a scenario, in which I need to throw an exception when a method returns a null object and also customise the response based on the parameters sent to the method.

I have an interface which has some methods, now i want to ensure that whoever implements that method does a basic check (defined by annotation or something like that) like null check is assigned. So that after the overridden method is call that check is invoked

For example:

@NotNull
User getUser(Integer id)

if response is Null then
"User not available for id:" + id

I've tried using javax validation @NotNull but it doesn't provide the parameters sent to method, is there any way to achieve that using javax validation.

Another thing, I tried was using AOP @Around control annotation and was successful to get the response and the parameters, wanted to ensure is there any other way to achieve that, as pointed out annotation on interface not possible on AOP LINK.

Another option is using decorator pattern but involves lots of boiler plate coding

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface MethodInterceptorBinding { }

@Interceptor
@MethodInterceptorBinding
public class MethodInterceptor {

    @AroundInvoke
   public Object validateMethodInvocation(InvocationContext ctx)
        throws Exception {

   }

}

Tried CDI but the MethodInterceptor is not getting invoked in the spring boot application, do i need to register these interceptors, if yes then how?

  • [CDI Interceptor](https://docs.oracle.com/javaee/7/tutorial/interceptors002.htm) could be used instead of Sring's AspectJ: [CDI Interceptor vs Spring AspectJ](https://www.baeldung.com/cdi-interceptor-vs-spring-aspectj), [Automatic Validation with Java EE Interceptors](https://www.sitepoint.com/using-java-bean-validation-method-parameters-return-values/) – MartinBG May 26 '20 at 16:08
  • Yes, interface annotations are not inherited by implementing classes. But Spring has an internal tool [AnnotationUtils](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/AnnotationUtils.html) which could help you determine the annotations you want to check during runtime. – kriegaex May 27 '20 at 09:11
  • Hi @kriegaex but annotation util wont get the method parameter – Ankit Pramod Singh May 27 '20 at 15:17
  • If your last comment was some kind of follow-up question, I do not understand it. If you would learn what an [MCVE](https://stackoverflow.com/help/mcve) is then then edit your question accordingly, your code would speak for itself and every capable developer could understand what you want to do, no matter what native language they speak. Wouldn't that be nice? You would get better answers that way. :-) – kriegaex May 28 '20 at 04:02

0 Answers0