Spring AOP - AspectJ - @AfterThrowing example

Last few pages talked about spring advices (before advice, after return advice, around advice and pointcut examples). In this page you will get an idea about how to integrate AspectJ annotations with Spring AOP framework. Using spring AOP and AspectJ, you can easily intercept methods.

AspectJ comes with below annotations:

1) @Before
2) @After
3) @AfterReturning
4) @AfterThrowing
5) @Around

In this page we will see an example for @AfterThrowing annotation. @AfterThrowing annotation intercepts method after throwing any exception

pom.xml file gives all required dependencies: Add dependencies for spring-aop jar, aspectjrt jar and aspectjweaver jar file.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
    http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SpringJavaBasedConfig</groupId>
    <artifactId>SpringJavaBasedConfig</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <spring.version>3.2.0.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.0</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.1</version>
        </dependency>

    </dependencies>
</project>

My business logic service class:

package com.java2novice.bean;

public class MyBusinessService {

    public String runMyBusinessLogic(){
        System.out.println("************************************");
        System.out.println("Running business logic...");
        System.out.println("************************************");

        return "Successfully executed my business logic";
    }

    public void testThrowException() {
        throw new NullPointerException();
    }
}

Here is the Aspect class example. The afterThrowing() method will be executed after any exception got throwed. Note here you have specified “throwing” attribute as part of your annotation. Make sure that the annotation throwing attribute value should be same as method input parameter.

package com.java2novice.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.ThrowsAdvice;

@Aspect
public class CatchThrowException implements ThrowsAdvice{

    @AfterThrowing(
    pointcut="execution(* com.java2novice.bean.MyBusinessService.testThrowException(..))", 
    throwing="excep")
    public void afterThrowing(JoinPoint joinPoint, Throwable excep) throws Throwable {
        System.out.println("Inside CatchThrowException.afterThrowing() method...");
        System.out.println("Running after throwing exception...");
        System.out.println("Exception : " + excep);
    }
}

Here is the xml based configuration file. By adding “<aop:aspectj-autoproxy />” tag, you can enable AspectJ with in your application. Add bean definitions for your normal bean and your Aspect.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <aop:aspectj-autoproxy />

    <bean id="busService" class="com.java2novice.bean.MyBusinessService" />
    <bean id="afterThrowAspectBean" class="com.java2novice.aop.CatchThrowException" />
 </beans>

Here is the final demo class:

package com.java2novice.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.java2novice.bean.MyBusinessService;

public class SpringDemo {

    public static void main(String a[]){

        String confFile = "applicationContext.xml";
        ConfigurableApplicationContext context = 
                            new ClassPathXmlApplicationContext(confFile);
        MyBusinessService busServ = (MyBusinessService) context.getBean("busService");
        try{
            busServ.testThrowException();
        } catch(Exception ex){

        }
    }
}

Output:

Inside CatchThrowException.afterThrowing() method...
Running after throwing exception...
Exception : java.lang.NullPointerException
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设我们有一个名为`UserService`的服务类,其中有一个方法`getUserById`用于根据用户ID获取用户信息。在这个方法中,我们想要使用`@AfterThrowing`切面来记录任何抛出的异常。 首先,我们需要在配置文件中启用`@Aspect`自动代理: ```xml <aop:aspectj-autoproxy /> ``` 然后,我们可以创建一个名为`ExceptionLogger`的切面类,其中包含一个名为`logException`的方法,用于记录异常信息: ```java import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; @Aspect public class ExceptionLogger { @AfterThrowing(pointcut = "execution(* com.example.UserService.getUserById(..))", throwing = "e") public void logException(JoinPoint joinPoint, Exception e) { System.out.println("Exception caught in " + joinPoint.getSignature().getName() + "(): " + e.getMessage()); } } ``` 在上面的代码中,我们使用了`@Aspect`注解来标记这是一个切面类,并使用了`@AfterThrowing`注解来定义一个切点,该切点匹配`UserService`类中的`getUserById`方法,并在该方法抛出异常时执行`logException`方法。 最后,我们需要将`ExceptionLogger`类注册为Spring bean,并将其作为切面应用于`UserService`类: ```xml <bean id="userService" class="com.example.UserService" /> <bean id="exceptionLogger" class="com.example.ExceptionLogger" /> <aop:config> <aop:aspect ref="exceptionLogger"> <aop:pointcut id="userServicePointcut" expression="bean(userService)" /> <aop:after-throwing pointcut-ref="userServicePointcut" method="logException" throwing="e" /> </aop:aspect> </aop:config> ``` 现在,当`getUserById`方法抛出异常时,异常信息将被记录到控制台中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值