CDI Interceptor vs Spring AspectJ – CDI拦截器 VS Spring AspectJ

最后修改: 2016年 8月 17日


1. Introduction


The Interceptor pattern is generally used to add new, cross-cutting functionality or logic in an application, and has solid support in a large number of libraries.


In this article, we’ll cover and contrast two of these major libraries: CDI interceptors and Spring AspectJ.

在这篇文章中,我们将介绍和对比这些主要库中的两个。CDI拦截器和Spring AspectJ。

2. CDI Interceptor Project Setup


CDI is officially supported for Jakarta EE but some implementations provide support to use CDI in Java SE environment. Weld can be considered as one example of CDI implementation which is supported in Java SE.

CDI被正式支持在Jakarta EE中,但是一些实现提供了在Java SE环境中使用CDI的支持。Weld可以看作是在Java SE中支持的CDI实现的一个例子。

In order to use CDI we need to import the Weld library in our POM:



The most recent Weld library can be found in the Maven repository.


Let’s now create a simple interceptor.


3. Introducing the CDI Interceptor


In order to designate classes we needed to intercept, let’s create the interceptor binding:


@Target( { METHOD, TYPE } )
@Retention( RUNTIME )
public @interface Audited {

After we’ve defined the interceptor binding we need to define the actual interceptor implementation:


public class AuditedInterceptor {
    public static boolean calledBefore = false;
    public static boolean calledAfter = false;

    public Object auditMethod(InvocationContext ctx) throws Exception {
        calledBefore = true;
        Object result = ctx.proceed();
        calledAfter = true;
        return result;

Every @AroundInvoke method takes a javax.interceptor.InvocationContext argument, returns a java.lang.Object, and can throw an Exception.


And so, when we annotate a method with the new @Audit interface, auditMethod will be invoked first, and only then the target method proceeds as well.


4. Apply the CDI Interceptor


Let’s apply the created interceptor on some business logic:


public class SuperService {
    public String deliverService(String uid) {
        return uid;

We’ve created this simple service and annotated the method we wanted to intercept with the @Audited annotation.


To enable the CDI interceptor one need to specify the full class name in the beans.xml file, located in the META-INF directory:


<beans xmlns=""

To validate that interceptor has indeed worked let’s now run the following test:


public class TestInterceptor {
    Weld weld;
    WeldContainer container;

    public void init() {
        weld = new Weld();
        container = weld.initialize();

    public void shutdown() {

    public void givenTheService_whenMethodAndInterceptorExecuted_thenOK() {
        SuperService superService =;
        String code = "123456";

In this quick test, we first get the bean SuperService from the container, then invoke business method deliverService on it and check that interceptor AuditedInterceptor was actually called by validating its state variables.

在这个快速测试中,我们首先从容器中获取Bean SuperService,然后对其调用业务方法deliverService,并通过验证其状态变量检查拦截器AuditedInterceptor是否真的被调用。

Also we have @Before and @After annotated methods in which we initialize and shutdown Weld container respectively.


5. CDI Considerations


We can point out the following advantages of CDI interceptors:


  • It is a standard feature of Jakarta EE specification
  • Some CDI implementations libraries can be used in Java SE
  • Can be used when our project has severe limitations on third-party libraries

The disadvantages of the CDI interceptors are the following:


  • Tight coupling between class with business logic and interceptor
  • Hard to see which classes are intercepted in the project
  • Lack of flexible mechanism to apply interceptors to a group of methods

6. Spring AspectJ

6.Spring AspectJ[/strong

Spring supports a similar implementation of interceptor functionality using AspectJ syntax as well.


First we need to add the following Spring and AspectJ dependencies to POM:



The most recent versions of Spring context, aspectjweaver can be found in the Maven repository.

Spring contextaspectjweaver的最新版本可以在Maven资源库中找到。

We can now create a simple aspect using AspectJ annotation syntax:


public class SpringTestAspect {
    private List accumulator;

    @Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))")
    public Object auditMethod(ProceedingJoinPoint jp) throws Throwable {
        String methodName = jp.getSignature().getName();
        accumulator.add("Call to " + methodName);
        Object obj = jp.proceed();
        accumulator.add("Method called successfully: " + methodName);
        return obj;

We created an aspect which applies to all the methods of SpringSuperService class – which, for simplicity, looks like this:


public class SpringSuperService {
    public String getInfoFromService(String code) {
        return code;

7. Spring AspectJ Aspect Apply

7.Spring AspectJ Aspect Apply

In order to validate that aspect really applies to the service, let’s write the following unit test:


@ContextConfiguration(classes = { AppConfig.class })
public class TestSpringInterceptor {
    SpringSuperService springSuperService;

    private List accumulator;

    public void givenService_whenServiceAndAspectExecuted_thenOk() {
        String code = "123456";
        String result = springSuperService.getInfoFromService(code);
        Assert.assertThat(accumulator.size(), is(2));
        Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService"));
        Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService"));

In this test we inject our service, call the method and check the result.


Here’s what the configuration looks like:


public class AppConfig {
    public SpringSuperService springSuperService() {
        return new SpringSuperService();

    public SpringTestAspect springTestAspect() {
        return new SpringTestAspect();

    public List getAccumulator() {
        return new ArrayList();

One important aspect here in the @EnableAspectJAutoProxy annotation – which enables support for handling components marked with AspectJ’s @Aspect annotation, similar to functionality found in Spring’s XML element.


8. Spring AspectJ Considerations

8.Spring AspectJ的注意事项

Let’s point out a few of the advantages of using Spring AspectJ:

让我们指出使用Spring AspectJ的一些优势。

  • Interceptors are decoupled from the business logic
  • Interceptors can benefit from dependency injection
  • Interceptor has all the configuration information in itself
  • Adding new interceptors wouldn’t require augmenting existing code
  • Interceptor has flexible mechanism to choose which methods to intercept
  • Can be used without Jakarta EE

And of course a few of the disadvantages:


  • You need to know the AspectJ syntax to develop interceptors
  • The Learning curve for the AspectJ interceptors is higher than for the CDI interceptors

9. CDI Interceptor vs Spring AspectJ

9.CDI拦截器与Spring AspectJ的对比

If your current project uses Spring then considering Spring AspectJ is a good choice.

如果你目前的项目使用Spring,那么考虑Spring AspectJ是一个不错的选择。

If you are using a full-blown application server, or your project doesn’t use Spring (or other frameworks eg Google Guice) and is strictly Jakarta EE then there is nothing left than to choose the CDI interceptor.

如果你使用的是一个完整的应用服务器,或者你的项目没有使用Spring(或其他框架,如Google Guice),而是严格意义上的Jakarta EE,那么除了选择CDI拦截器之外,就没有别的办法了。

10. Conclusion


In this article we have covered two implementations of interceptor pattern: CDI interceptor and Spring AspectJ. We have covered advantages and disadvantages each of them.

在这篇文章中,我们已经介绍了拦截器模式的两种实现。CDI拦截器和Spring AspectJ。我们已经介绍了它们各自的优势和劣势。

The source code for examples of this article can be found in our repository on GitHub.