DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • MicroProfile: What You Need to Know
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Java EE 6 Pet Catalog with GlassFish and MySQL
  • How To Create and Edit PDF Annotations in Java

Trending

  • A Better Web3 Experience: Account Abstraction From Flow (Part 2)
  • DevSecOps: Integrating Security Into Your DevOps Workflow
  • Top 7 Best Practices DevSecOps Team Must Implement in the CI/CD Process
  • API Design
  1. DZone
  2. Coding
  3. Java
  4. Java EE Interceptors

Java EE Interceptors

Abhishek Gupta user avatar by
Abhishek Gupta
CORE ·
Jan. 09, 15 · Interview
Like (3)
Save
Tweet
Share
29.10K Views

Join the DZone community and get the full member experience.

Join For Free

History

I think it’s important to take a look at the evolution of Interceptors in Java EE because of the simple fact that it started as an EJB-specific item and later evolved into a separate spec which is now open for extension by other Java EE specifications.

Version 1.0

Interceptors were first introduced in EJB 3.0 (part of Java EE 5). Interceptors did not have a dedicated spec but they were versioned 1.0 and bought basic AOP related features to managed beans (POJOs) via simple annotations

  • @AroundInvoke – to annotate methods containing the interception logic for target class methods
  • @Intercerptors – to bind the the interceptor classes with their target classes/methods
  • Capability to configure interceptors for an entire module (EJB JAR) via the deployment descriptor
  • @ExcludeDefaultInterceptors – to mute default interceptors defined in the deployment descriptor
  • @ExcludeClassInterceptors – to mute a globally defined (class level) interceptor for a particular method/constructor of the class

Interceptors 1.1

Along came Java EE 6 with EJB 3.1 – Interceptors 1.1 was still included in the EJB spec document

  • @InterceptorBinding – a type safe way of specifying interceptors of a class or a method. Please note that this annotation was leveraged by CDI 1.0 (another specification introduced in Java EE 6) and its details are present in the CDI 1.0 spec doc rather than EJB 3.1 (light bulb moment … at least for me)
  • @Interceptor – Used to explicitly declare a class containing an interception logic in a specific method (annotated with @AroundInvoke etc) as an interceptor along with an appropriate Interceptor Binding. This too was mentioned in the CDI 1.0 documentation only.
  • @AroundTimeout – used to intercept time outs of EJB timers along with a way to obtain an instance of the Timer being intercepted (viajavax.interceptor.InvocationContext.getTimer())

Interceptors 1.2

Interceptors were split off into an individual spec in Java EE 7 and thus Interceptors 1.2came into being

  • Interceptors 1.2 was a maintenance release on top of 1.1 and hence the JSR number still remained the same as EJB 3.1 (JSR 318)
  • Interceptor.Priority (static class) – to provide capability to define the order (priority) in which the interceptors need to invoked.
  • @AroundConstruct – used to intercept the construction of the target class i.e. invoke logic prior to the constructor of the target class is invoked

It’s important to bear in mind that Interceptors are applicable to managed beans in general. Managed Beans themselves are simple POJOs which are privileged to basic services by the container – Interceptors are one of them along with life cycle callbacks, resource injection.

Memory Aid

It’s helpful to think of Interceptors as components which can interpose on beans throughout their life cycle

  • before they are even constructed – @AroundConstruct
  • after they are constructed – @PostConstruct
  • during their life time (method invocation) – @AroundInvoke
  • prior to destruction – @PreDestroy
  • time outs of EJBs – @AroundTimeout

Blog_JavaEE_Interceptors

Let’s look at some of the traits of Interceptors in more detail and try to answer questions like

  • where are they applied and what do they intercept ?
  • how to bind interceptors to the target (class) they are supposed to intercept ?

Interceptors Types (based on the intercepted component)

Method Interceptors

  • Achieved by @AroundInvoke
    public class MethodInterceptor{
    	@AroundInvoke
    	public Object interceptorMethod(InvocationContext ictx) throws Exception{
    		//logic goes here
    	}
    }
     
    @Stateless
    public class AnEJB{
    	@Interceptors(MethodInterceptor.class)
    	public void bizMethod(){
    		//any calls to this method will be intercepted by MethodInterceptor.interceptorMethod()
    	}
    }
  • The method containing the logic can be part of separate class as well as the target class (class to be intercepted) itself.

Lifecycle Callback interceptors

  • Decorate the method with @AroundConstruct in order to intercept the constructor invocation for a class

    public class ConstructorInterceptor{
    	@AroundConstruct
    	public Object interceptorMethod(InvocationContext ictx) throws Exception{
    		//logic goes here
    	}
    }
     
    public class APOJO{
    	@Interceptors(ConstructorInterceptor.class)
    	public APOJO(){
    		//any calls to this constructor will be intercepted by ConstructorInterceptor.interceptorMethod()
    	}
    }
  • The method annotated with @AroundConstruct cannot be a part of the intercepted class. It has to be defined using a separate Interceptor class
  • Use the @PostConstruct annotation on a method in order to intercept a call back method on a managed bean. Just to clarify again – the Interceptor spec does not define a new annotation as such. One needs to reuse the @PostConstruct (part of theCommon Annotations spec) on the interceptor method.

    public class PostConstructInterceptor{
    	@PostConstruct
    	public void interceptorMethod(InvocationContext ictx) throws Exception{
    		//logic goes here
    	}
    }
     
    @Interceptors(PostConstructInterceptor.class)
    public class APOJO{
    	@PostConstruct
    	public void bizMethod(){
    		//any calls to this method will be intercepted by PostConstructInterceptor.interceptorMethod()
    	}
    }
  • The @PreDestroy (another call back annotation defined in Common Annotations spec) annotation is used in a similar fashion

Time-out Interceptors

  • As mentioned above – @AroundTimeout used to intercept time outs of EJB timers along with a way to obtain an instance of the Timer being intercepted (viajavax.interceptor.InvocationContext.getTimer())

Applying/Binding Interceptors

Using @Interceptors

  • As shown in above examples – just use the @Interceptors annotation to specify the interceptor classes
  • @Interceptors can be applied on a class level (automatically applicable to all the methods of a class), to a particular method or multiple methods and constructor in case of a constructor specific interceptor using @AroundConstruct

Using @IntercerptorBinding

  • Interceptor Bindings (explained above) – Use @IntercerptorBinding annotation to define a binding annotation which is further used on the interceptor class as well as the target class (whose method, constructor etc needs to be intercepted)

    @InterceptorBinding 
    @Target({TYPE, METHOD, CONSTRUCTOR}) 
    @Retention(RUNTIME) 
    public @interface @Auditable {
    }
     
    @Auditable 
    @Interceptor
    public class AuditInterceptor {
    	@AroundInvoke
    	public Object audit(InvocationContext ictx) throws Exception{
    		//logic goes here
    	}
    }
     
    @Stateless
    @Auditable
    public class AnEJB{
    	public void bizMethod(){
    		//any calls to this method will be intercepted by AuditInterceptor.audit()
    	}
    }
Deployment Descriptor

One can also use deployment descriptors to bind interceptors and target classes either in an explicit fashion as well as in override mode to annotations.

This was a rather quick overview of Java EE interceptors. Hopefully the right trigger for you to dig deeper :-)

Cheers !

Java EE Java (programming language) Annotation Deployment descriptor

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • MicroProfile: What You Need to Know
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Java EE 6 Pet Catalog with GlassFish and MySQL
  • How To Create and Edit PDF Annotations in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: