spring的aop中提供了强大的处理机制,今天就利用spring的@Around注解实现自己的异常处理机制,使我们的代码变得更加简洁,避免代码重复使用try catch,
首先定义一个切面,对我们感兴趣的方法尽行拦截
package com; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; /** * Created by zoujianglin * 2018/8/21 0021. */ @Component @Aspect public class Aop { //代表拦截com包下,一个名叫lin类的所有方法 @Pointcut("execution(public * com.lin.*(..))") public void pointCut() { } @Before("pointCut()") public void begin() { System.out.println("开启事务"); } /* @After("pointCut()") public void close() { System.out.println("关闭事务"); } */ //环绕通知,实现自己的异常处理器 @Around("execution(public * com.lin.*(..))") public <T> T Exception(ProceedingJoinPoint pjp) { try { return (T)pjp.proceed(); } catch (Exception e) { System.out.println("有异常"); } catch (Throwable throwable) { System.out.println("有异常"); } return null; } }
接着在com包下定义一个名为lin的类
package com; import org.springframework.stereotype.Component; /** * Created by zoujianglin * 2018/8/21 0021. */ @Component public class lin implements linInterface { public int save(){ throw new RuntimeException("test"); // System.out.print(""); // return 1; } }
接口如下
package com; /** * Created by zoujianglin * 2018/8/21 0021. */ public interface linInterface { public int save(); }
下面进行测试
import com.lin; import com.linInterface; import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by zoujianglin * 2018/8/21 0021. */ public class testPro { public static void main(String[] args) { ApplicationContext a = new ClassPathXmlApplicationContext("applicationContext.xml"); linInterface lin1 = (linInterface) a.getBean("lin"); int t = lin1.save(); System.out.print(t); } }
//运行发现并没有异常抛出,方法异常已被异常处理器所拦截,对于更复杂的逻辑,可以在上面的代码稍加修改即可使用,
applicationContext.xml配置文件如下
<?xml version="1.0" encoding="UTF-8"?> <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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com"></context:component-scan> <!--需要引入该配置 否则aop不会生效--> <aop:aspectj-autoproxy/> <!-- aop测试,需要引入aop命名空间 --> </beans>