Java EE. Interceptor and new


As you know, in Java EE there are interceptors. An interceptor is a class that intercepts method calls to the target class and "wraps" them in some additional functionality. For example, the @Transactional annotation "wraps" the call to the intercepted methods in a transaction.

But the interceptors only work when the target object is created by the container. If an object is created using new, the interceptor is not applied.

What is it what should I do when an instance of a class is produced by a factory (annotation @Produces) that calls new? How do I" bind " the interceptors to objects created by the factory using the new operator?

Author: Visman, 2016-12-09

1 answers

I see the use of interseptors in a more global sense, that is, for example, when using the DAO level, Service, Controller, while using Spring with annotations @Autowire, each call will be intercepted by the corresponding interceptor, for example:

@Aspect
...
        @Around("execution(* com.mycompany.controller.*.*(..))")
        public Object interceptController(ProceedingJoinPoint pjp) throws Throwable {
                try {
                  result = pjp.proceed();
                } catch (Exception ex) {
                                       }
        return result

        }

This is useful to use to catch all Exceptions for a general style of handling them. But any other logic can be used for example to find a spy :).

In your case, if I understand correctly, you want to wrap the execution of a method of a class in interceptor and the class will be created by the operator new. In this case, I advise you to write your own custom interceptor, there is even a programming pattern for this purpose. It is called Proxy.

Https://www.tutorialspoint.com/design_pattern/proxy_pattern.htm

In a nutshell, I will tell you how I see the implementation. There is a common interface between the object on which there will be the method and interceptor that will intercept will be called.

In the interseptor, there will be a reference to the object and it will also call the method on the real object after or before the corresponding function is executed. logic in the interceptore. Next, you just need to set the real object in interceptor and use it as a real object, this will work because they have a common interface.

 3
Author: Arch, 2017-11-12 10:55:25