AOP异常捕获

第一次加入博客园,开始将所遇到的东西写出来,不仅日后自己能看,也希望能帮助到其他人,嘿嘿!

AOP:面向切面编程(也叫面向方面):Aspect Oriented Programming(AOP),是目前软件开发中的一个热点,也是Spring框架中的一个重要内容。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 AOP是OOP的延续,是(Aspect Oriented Programming)的缩写,意思是面向切面(方面)编程。

对于AOP编程,网上有很多介绍可以去看。

关于spring aop方式拦截service层的方法。

1、在spring-config.xml里配置相关的aop设置。

 1 <!--设置service层的拦截器 bean-->
 2  <bean id="logAspect" class="com.log.util.LogInterceptor" ></bean
 3 
 4 <!--采用spring aop方式拦截service层的方法-->
 5 <aop:config proxy-target-class="false">
 6    <aop:pointcut id="pointcut-except" expression="execution(* com..service..*.*(..))" />
 7    <aop:advisor advice-ref="texAdvice" pointcut-ref="pointcut-except" order="9" />
 8    <aop:aspect id="exceptAspect" ref="logAspect"  order="3" >
 9     <aop:after-throwing prointcut-ref="pointcut-except" method="doThrowing"   throwing="ex" />
10    </aop:aspect>
11 <aop:config>
12    

2、添加拦截器bean里的doThrowing方法。

//捕获异常的方法
public void doThrowing(JoinPoint pjp,Throwable ex){
    
    String classname = pjp.getTarget().getClass().getSimpleName();//出错类名
    String methodname = pjp.getSignature().getName();//出错方法名
    String  exname = ex.getClass().getName();//异常名称
    String  message = ex.getMessage();//异常信息

}    
View Code

 即可在Service层捕获异常后,到拦截器的doThrowing()方法做处理,这里可以添加表将异常信息记录到表中。

3、测试

添加Service层,在其实现类中添加测试代码,运行后,即可捕获到java.lang.NumberFormatException的异常。

public void test(){
   String num = null;
   int num1 = Integer.parseInt(num);
}

 

posted on 2015-09-16 13:42  sierrajuan2015  阅读(1808)  评论(0)    收藏  举报

导航