spring AOP的异常拦截

springaopexceptionuserobjectdao

系统的异常处理机制是衡量一个系统设计的关键因素,良好的异常处理机制能在系统出现异常时准确的找到问题的所在。

spring aop对异常的处理有良好的支持。spring 提供了一个接口 ThrowsAdvice,该接口里面没有任何方法,但是实现类里面必须的实现

afterThrowing(Method method, Object[] args, Object target, RuntimeException throwable) 或者

afterThrowing(RuntimeException throwable)

如果需要记录发生异常方法的详细信息,则实现第一个方法就行,如果只记录发生的异常,实现第二个方法就ok!

那么异常的处理应该在什么位置来做处理呢?

一般我们的系统都应该有以下几个层次:Action--->Service---->DAO

DAO负责直接和数据库打交道,也是发生异常频率较高的地方,而service只是调用DAO所提供给外面的接口,action里面大部分的操作也是调用service的服务,再加上少数其他的逻辑,这部分的异常可以单独处理!下面我们主要关心DAO层的异常处理。

1、定义接口

  1. package com.beckham.dao;
  2. import java.util.List;
  3. import com.beckham.model.User;
  4. /**
  5. * @author Owner
  6. * Jan 19, 2010 10:15:32 PM
  7. *
  8. * struts2
  9. * com.beckham.dao
  10. * UserDAO.java
  11. */
  12. public interface UserDAO {
  13. public boolean userExsit(String username)throws Exception;
  14. public User findById(int id)throws Exception;
  15. public List<User> queryUser(String hql,int beginIndex)throws Exception;
  16. public void saveUser(User user)throws Exception;
  17. public int gettotalSize(String hql)throws Exception ;
  18. }
package com.beckham.dao; import java.util.List; import com.beckham.model.User; /** * @author Owner * Jan 19, 2010 10:15:32 PM * * struts2 * com.beckham.dao * UserDAO.java */ public interface UserDAO { public boolean userExsit(String username) throws Exception; public User findById(int id) throws Exception; public List<User> queryUser(String hql,int beginIndex) throws Exception; public void saveUser(User user) throws Exception; public int gettotalSize(String hql) throws Exception ; }

2、实现

  1. package com.beckham.daoimp;
  2. import java.util.List;
  3. import com.beckham.dao.SuperDAO;
  4. import com.beckham.dao.UserDAO;
  5. import com.beckham.model.User;
  6. import com.beckham.util.PropertyUtil;
  7. /**
  8. * @author Owner
  9. * Jan 19, 2010 10:15:50 PM
  10. *
  11. * struts2
  12. * com.beckham.daoimp
  13. * UserDAOImp.java
  14. */
  15. public class UserDAOImpextends SuperDAO implements UserDAO {
  16. public User findById(int id)throws Exception {
  17. User user = null;
  18. try {
  19. user = (User) this.getHibernateTemplate().get(User.class, id);
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. throw new Exception("主键查询用户失败", e);
  23. }
  24. return user;
  25. }
  26. public void saveUser(User user)throws Exception {
  27. try {
  28. this.getHibernateTemplate().save(user);
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. throw new Exception("增加用户失败", e);
  32. }
  33. }
  34. @SuppressWarnings("unchecked")
  35. public List<User> queryUser(String hql,int beginIndex) throws Exception {
  36. try {
  37. return (List<User>)this.getHibernateTemplate().getSessionFactory()
  38. .getCurrentSession().createQuery(hql).setFirstResult(
  39. beginIndex).setMaxResults(
  40. PropertyUtil.getPageSize()).list();
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. throw new Exception("查询用户出现异常", e);
  44. }
  45. }
  46. public boolean userExsit(String username)throws Exception {
  47. boolean bl = true;
  48. String hql = "from User where username='" + username +"'";
  49. if (queryUser(hql,0).size() == 0) {
  50. bl = false;
  51. }
  52. return bl;
  53. }
  54. public int gettotalSize(String hql)throws Exception {
  55. int totalsize = 0;
  56. try {
  57. totalsize = Integer.parseInt(this.getHibernateTemplate().find(hql)
  58. .get(0).toString());
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. throw new Exception("查询用户总数失败", e);
  62. }
  63. return totalsize;
  64. }
  65. }
package com.beckham.daoimp; import java.util.List; import com.beckham.dao.SuperDAO; import com.beckham.dao.UserDAO; import com.beckham.model.User; import com.beckham.util.PropertyUtil; /** * @author Owner * Jan 19, 2010 10:15:50 PM * * struts2 * com.beckham.daoimp * UserDAOImp.java */ public class UserDAOImp extends SuperDAO implements UserDAO { public User findById(int id) throws Exception { User user = null; try { user = (User) this.getHibernateTemplate().get(User.class, id); } catch (Exception e) { e.printStackTrace(); throw new Exception("主键查询用户失败", e); } return user; } public void saveUser(User user) throws Exception { try { this.getHibernateTemplate().save(user); } catch (Exception e) { e.printStackTrace(); throw new Exception("增加用户失败", e); } } @SuppressWarnings("unchecked") public List<User> queryUser(String hql, int beginIndex) throws Exception { try { return (List<User>) this.getHibernateTemplate().getSessionFactory() .getCurrentSession().createQuery(hql).setFirstResult( beginIndex).setMaxResults( PropertyUtil.getPageSize()).list(); } catch (Exception e) { e.printStackTrace(); throw new Exception("查询用户出现异常", e); } } public boolean userExsit(String username) throws Exception { boolean bl = true; String hql = "from User where username='" + username + "'"; if (queryUser(hql, 0).size() == 0) { bl = false; } return bl; } public int gettotalSize(String hql) throws Exception { int totalsize = 0; try { totalsize = Integer.parseInt(this.getHibernateTemplate().find(hql) .get(0).toString()); } catch (Exception e) { e.printStackTrace(); throw new Exception("查询用户总数失败", e); } return totalsize; } }

这里需要说明的是,这里的异常我没有细致的分类,都是throws Exception。

service层的代码就省略了,因为只是调用DAO层的方法,下面来写异常的拦截

  1. package com.beckham.aop;
  2. import java.lang.reflect.Method;
  3. import org.springframework.aop.ThrowsAdvice;
  4. /**
  5. * @author Owner Jan 18, 2010 2:37:10 PM 处理DAO层的异常 struts2 com.beckham.aop
  6. * ExceptionLog.java
  7. */
  8. public class ExceptionLogimplements ThrowsAdvice {
  9. /**
  10. * Owner
  11. * 参数解释 Method method 执行的方法
  12. * Object[] args 方法参数
  13. * Object target 代理的目标对象
  14. * Throwable throwable 产生的异常
  15. * Jan 18, 2010 3:21:46 PM
  16. */
  17. public void afterThrowing(Method method, Object[] args, Object target,
  18. RuntimeException throwable) {
  19. System.out.println("产生异常的方法名称: " + method.getName());
  20. for(Object o:args){
  21. System.out.println("方法的参数: " + o.toString());
  22. }
  23. System.out.println("代理对象: " + target.getClass().getName());
  24. System.out.println("抛出的异常: " + throwable.getMessage()+">>>>>>>"
  25. + throwable.getCause());
  26. System.out.println("异常详细信息:   "+throwable.fillInStackTrace());
  27. }
  28. }
package com.beckham.aop; import java.lang.reflect.Method; import org.springframework.aop.ThrowsAdvice; /** * @author Owner Jan 18, 2010 2:37:10 PM 处理DAO层的异常 struts2 com.beckham.aop * ExceptionLog.java */ public class ExceptionLog implements ThrowsAdvice { /** * Owner * 参数解释 Method method 执行的方法 * Object[] args 方法参数 * Object target 代理的目标对象 * Throwable throwable 产生的异常 * Jan 18, 2010 3:21:46 PM */ public void afterThrowing(Method method, Object[] args, Object target, RuntimeException throwable) { System.out.println("产生异常的方法名称: " + method.getName()); for(Object o:args){ System.out.println("方法的参数: " + o.toString()); } System.out.println("代理对象: " + target.getClass().getName()); System.out.println("抛出的异常: " + throwable.getMessage()+">>>>>>>" + throwable.getCause()); System.out.println("异常详细信息:   "+throwable.fillInStackTrace()); } }

最后当然就是在配置文件里面配置了

  1. <beanid="log"class="com.beckham.aop.LogAdvice"></bean>
  2. <bean id="exceptionLog"class="com.beckham.aop.ExceptionLog"></bean>
  3. <!-- beanName自动代理 -->
  4. <bean id="logAdvice"
  5. class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  6. <propertyname="beanNames">
  7. <list>
  8. <value>userDAO</value>
  9. </list>
  10. </property>
  11. <propertyname="interceptorNames">
  12. <list>
  13. <value>log</value>
  14. <value>exceptionLog</value>
  15. </list>
  16. </property>
  17. </bean>
<bean id="log" class="com.beckham.aop.LogAdvice"></bean> <bean id="exceptionLog" class="com.beckham.aop.ExceptionLog"></bean> <!-- beanName自动代理 --> <bean id="logAdvice" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <list> <value>userDAO</value> </list> </property> <property name="interceptorNames"> <list> <value>log</value> <value>exceptionLog</value> </list> </property> </bean>

到此,通过spring AOP拦截异常就完成了,这里只是拦截DAO层的异常,此方法的好处就是处理异常和功能实现完全分离开,只需要在写方法的时候要记得抛出相应的异常,当出现异常时ThrowsAdvice就会拦截到该异常,并获取该异常的详细信息。

这里贴出我测试可以使用的配置:

<bean id="exceptionLog" class="net.chinanets.utils.AopExceptionHandler"></bean>
<!-- beanName自动代理 -->
<bean id="logAdvice"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>exceptionLog</value>
</list>
</property>
</bean>


注:

<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>

<value>*Service</value>可以拦截所有的service

*Service匹配你beans.xml中配置的所有bean的ID

这里的切入点是匹配beans ID比较简便,如果从文件路径切入可能会各种报错。

系统的异常处理机制是衡量一个系统设计的关键因素,良好的异常处理机制能在系统出现异常时准确的找到问题的所在。

spring aop对异常的处理有良好的支持。spring 提供了一个接口 ThrowsAdvice,该接口里面没有任何方法,但是实现类里面必须的实现

afterThrowing(Method method, Object[] args, Object target, RuntimeException throwable) 或者

afterThrowing(RuntimeException throwable)

如果需要记录发生异常方法的详细信息,则实现第一个方法就行,如果只记录发生的异常,实现第二个方法就ok!

那么异常的处理应该在什么位置来做处理呢?

一般我们的系统都应该有以下几个层次:Action--->Service---->DAO

DAO负责直接和数据库打交道,也是发生异常频率较高的地方,而service只是调用DAO所提供给外面的接口,action里面大部分的操作也是调用service的服务,再加上少数其他的逻辑,这部分的异常可以单独处理!下面我们主要关心DAO层的异常处理。

1、定义接口

  1. package com.beckham.dao;
  2. import java.util.List;
  3. import com.beckham.model.User;
  4. /**
  5. * @author Owner
  6. * Jan 19, 2010 10:15:32 PM
  7. *
  8. * struts2
  9. * com.beckham.dao
  10. * UserDAO.java
  11. */
  12. public interface UserDAO {
  13. public boolean userExsit(String username)throws Exception;
  14. public User findById(int id)throws Exception;
  15. public List<User> queryUser(String hql,int beginIndex)throws Exception;
  16. public void saveUser(User user)throws Exception;
  17. public int gettotalSize(String hql)throws Exception ;
  18. }
package com.beckham.dao; import java.util.List; import com.beckham.model.User; /** * @author Owner * Jan 19, 2010 10:15:32 PM * * struts2 * com.beckham.dao * UserDAO.java */ public interface UserDAO { public boolean userExsit(String username) throws Exception; public User findById(int id) throws Exception; public List<User> queryUser(String hql,int beginIndex) throws Exception; public void saveUser(User user) throws Exception; public int gettotalSize(String hql) throws Exception ; }

2、实现

  1. package com.beckham.daoimp;
  2. import java.util.List;
  3. import com.beckham.dao.SuperDAO;
  4. import com.beckham.dao.UserDAO;
  5. import com.beckham.model.User;
  6. import com.beckham.util.PropertyUtil;
  7. /**
  8. * @author Owner
  9. * Jan 19, 2010 10:15:50 PM
  10. *
  11. * struts2
  12. * com.beckham.daoimp
  13. * UserDAOImp.java
  14. */
  15. public class UserDAOImpextends SuperDAO implements UserDAO {
  16. public User findById(int id)throws Exception {
  17. User user = null;
  18. try {
  19. user = (User) this.getHibernateTemplate().get(User.class, id);
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. throw new Exception("主键查询用户失败", e);
  23. }
  24. return user;
  25. }
  26. public void saveUser(User user)throws Exception {
  27. try {
  28. this.getHibernateTemplate().save(user);
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. throw new Exception("增加用户失败", e);
  32. }
  33. }
  34. @SuppressWarnings("unchecked")
  35. public List<User> queryUser(String hql,int beginIndex) throws Exception {
  36. try {
  37. return (List<User>)this.getHibernateTemplate().getSessionFactory()
  38. .getCurrentSession().createQuery(hql).setFirstResult(
  39. beginIndex).setMaxResults(
  40. PropertyUtil.getPageSize()).list();
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. throw new Exception("查询用户出现异常", e);
  44. }
  45. }
  46. public boolean userExsit(String username)throws Exception {
  47. boolean bl = true;
  48. String hql = "from User where username='" + username +"'";
  49. if (queryUser(hql,0).size() == 0) {
  50. bl = false;
  51. }
  52. return bl;
  53. }
  54. public int gettotalSize(String hql)throws Exception {
  55. int totalsize = 0;
  56. try {
  57. totalsize = Integer.parseInt(this.getHibernateTemplate().find(hql)
  58. .get(0).toString());
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. throw new Exception("查询用户总数失败", e);
  62. }
  63. return totalsize;
  64. }
  65. }
package com.beckham.daoimp; import java.util.List; import com.beckham.dao.SuperDAO; import com.beckham.dao.UserDAO; import com.beckham.model.User; import com.beckham.util.PropertyUtil; /** * @author Owner * Jan 19, 2010 10:15:50 PM * * struts2 * com.beckham.daoimp * UserDAOImp.java */ public class UserDAOImp extends SuperDAO implements UserDAO { public User findById(int id) throws Exception { User user = null; try { user = (User) this.getHibernateTemplate().get(User.class, id); } catch (Exception e) { e.printStackTrace(); throw new Exception("主键查询用户失败", e); } return user; } public void saveUser(User user) throws Exception { try { this.getHibernateTemplate().save(user); } catch (Exception e) { e.printStackTrace(); throw new Exception("增加用户失败", e); } } @SuppressWarnings("unchecked") public List<User> queryUser(String hql, int beginIndex) throws Exception { try { return (List<User>) this.getHibernateTemplate().getSessionFactory() .getCurrentSession().createQuery(hql).setFirstResult( beginIndex).setMaxResults( PropertyUtil.getPageSize()).list(); } catch (Exception e) { e.printStackTrace(); throw new Exception("查询用户出现异常", e); } } public boolean userExsit(String username) throws Exception { boolean bl = true; String hql = "from User where username='" + username + "'"; if (queryUser(hql, 0).size() == 0) { bl = false; } return bl; } public int gettotalSize(String hql) throws Exception { int totalsize = 0; try { totalsize = Integer.parseInt(this.getHibernateTemplate().find(hql) .get(0).toString()); } catch (Exception e) { e.printStackTrace(); throw new Exception("查询用户总数失败", e); } return totalsize; } }

这里需要说明的是,这里的异常我没有细致的分类,都是throws Exception。

service层的代码就省略了,因为只是调用DAO层的方法,下面来写异常的拦截

  1. package com.beckham.aop;
  2. import java.lang.reflect.Method;
  3. import org.springframework.aop.ThrowsAdvice;
  4. /**
  5. * @author Owner Jan 18, 2010 2:37:10 PM 处理DAO层的异常 struts2 com.beckham.aop
  6. * ExceptionLog.java
  7. */
  8. public class ExceptionLogimplements ThrowsAdvice {
  9. /**
  10. * Owner
  11. * 参数解释 Method method 执行的方法
  12. * Object[] args 方法参数
  13. * Object target 代理的目标对象
  14. * Throwable throwable 产生的异常
  15. * Jan 18, 2010 3:21:46 PM
  16. */
  17. public void afterThrowing(Method method, Object[] args, Object target,
  18. RuntimeException throwable) {
  19. System.out.println("产生异常的方法名称: " + method.getName());
  20. for(Object o:args){
  21. System.out.println("方法的参数: " + o.toString());
  22. }
  23. System.out.println("代理对象: " + target.getClass().getName());
  24. System.out.println("抛出的异常: " + throwable.getMessage()+">>>>>>>"
  25. + throwable.getCause());
  26. System.out.println("异常详细信息:   "+throwable.fillInStackTrace());
  27. }
  28. }
package com.beckham.aop; import java.lang.reflect.Method; import org.springframework.aop.ThrowsAdvice; /** * @author Owner Jan 18, 2010 2:37:10 PM 处理DAO层的异常 struts2 com.beckham.aop * ExceptionLog.java */ public class ExceptionLog implements ThrowsAdvice { /** * Owner * 参数解释 Method method 执行的方法 * Object[] args 方法参数 * Object target 代理的目标对象 * Throwable throwable 产生的异常 * Jan 18, 2010 3:21:46 PM */ public void afterThrowing(Method method, Object[] args, Object target, RuntimeException throwable) { System.out.println("产生异常的方法名称: " + method.getName()); for(Object o:args){ System.out.println("方法的参数: " + o.toString()); } System.out.println("代理对象: " + target.getClass().getName()); System.out.println("抛出的异常: " + throwable.getMessage()+">>>>>>>" + throwable.getCause()); System.out.println("异常详细信息:   "+throwable.fillInStackTrace()); } }

最后当然就是在配置文件里面配置了

  1. <beanid="log"class="com.beckham.aop.LogAdvice"></bean>
  2. <bean id="exceptionLog"class="com.beckham.aop.ExceptionLog"></bean>
  3. <!-- beanName自动代理 -->
  4. <bean id="logAdvice"
  5. class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  6. <propertyname="beanNames">
  7. <list>
  8. <value>userDAO</value>
  9. </list>
  10. </property>
  11. <propertyname="interceptorNames">
  12. <list>
  13. <value>log</value>
  14. <value>exceptionLog</value>
  15. </list>
  16. </property>
  17. </bean>
<bean id="log" class="com.beckham.aop.LogAdvice"></bean> <bean id="exceptionLog" class="com.beckham.aop.ExceptionLog"></bean> <!-- beanName自动代理 --> <bean id="logAdvice" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <list> <value>userDAO</value> </list> </property> <property name="interceptorNames"> <list> <value>log</value> <value>exceptionLog</value> </list> </property> </bean>

到此,通过spring AOP拦截异常就完成了,这里只是拦截DAO层的异常,此方法的好处就是处理异常和功能实现完全分离开,只需要在写方法的时候要记得抛出相应的异常,当出现异常时ThrowsAdvice就会拦截到该异常,并获取该异常的详细信息。

这里贴出我测试可以使用的配置:

<bean id="exceptionLog" class="net.chinanets.utils.AopExceptionHandler"></bean>
<!-- beanName自动代理 -->
<bean id="logAdvice"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>exceptionLog</value>
</list>
</property>
</bean>


注:

<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>

<value>*Service</value>可以拦截所有的service

*Service匹配你beans.xml中配置的所有bean的ID

这里的切入点是匹配beans ID比较简便,如果从文件路径切入可能会各种报错。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值