Exception blocking for spring AOP

Source: Internet
Author: User
Tags aop exception handling throwable

The system's exception handling mechanism is the key factor to measure a system design, and the good exception handling mechanism can find the problem exactly when the system is abnormal.

Spring AOP has good support for exception handling. Spring provides an interface Throwsadvice, which does not have any methods, but implements that must be implemented within the class

Afterthrowing (method, object[] args, Object target, runtimeexception throwable) or

Afterthrowing (runtimeexception throwable)

If the details of the exception method need to be logged, the first method is implemented, and if only the exception is logged, the implementation of the second method is OK.

So where does the exception handle should be handled?

Generally our system should have the following levels: Action--->service---->dao

DAO is responsible for dealing directly with the database, but also where the abnormal frequency is high, and the service is just called the interface provided by DAO, the action inside most of the operation is called service services, coupled with a few other logic, this part of the exception can be handled separately. Below we mainly care about the DAO layer exception handling.

1. Define the interface

Package Com.beckham.dao; Import java.util.List; Import Com.beckham.model.User; /** * @author Owner * Jan, 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. Realize

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, 10:15:50 PM * * struts2 * COM.BECKHAM.DAOIMP * Userdaoimp.java * * public class Userdaoi MP extends Superdao implements Userdao {public User findbyid (int id) throws Exception {User user = null; try {user = (U Ser) this.gethibernatetemplate (). Get (User.class, id); } catch (Exception e) {e.printstacktrace (); throw new Exception ("PRIMARY key query user failed", e);} return user; The public void Saveuser (user user) throws Exception {try {this.gethibernatetemplate (). Save (user);} catch (Exception e) { E.printstacktrace (); throw new Exception ("Increase user failure", 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 ("Query user 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.gethib Ernatetemplate (). Find (HQL). Get (0). toString ()); } catch (Exception e) {e.printstacktrace (); throw new Exception ("failed to query the total number of users", e);} return totalsize; } }

What needs to be explained here is that the exception here I do not have a detailed classification, are throws Exception.

The service layer code is omitted, because just call the DAO layer method, the following to write the exception of the interception

Package COM.BECKHAM.AOP; Import Java.lang.reflect.Method; Import Org.springframework.aop.ThrowsAdvice; /** * @author Owner Jan, 2:37:10 PM exception to the DAO layer struts2 COM.BECKHAM.AOP * Exceptionlog.java * * public class Exceptio NLog implements Throwsadvice {/** * Owner * parameter explains method performed methods * object[] Args method parameter * Object Target agent * Throw Able Throwable generated anomalies * Jan, 3:21:46 PM */public void afterthrowing (method, object[] args, Object target, R Untimeexception throwable) {System.out.println ("method name to generate exception:" + Method.getname ()); for (Object O:args) {System.out.println ("parameter of Method:" + o.tostring ());} System.out.println ("proxy object:" + Target.getclass (). GetName ()); System.out.println ("Thrown exception:" + throwable.getmessage () + ">>>>>>>" + throwable.getcause ()); SYSTEM.OUT.PRINTLN ("Exception Details:" +throwable.fillinstacktrace ());}}

Finally, of course, it is configured in the config file.

<bean id= "Log" class= "Com.beckham.aop.LogAdvice" ></bean> <bean id= "Exceptionlog" class= " Com.beckham.aop.ExceptionLog "></bean> <!--beanname Auto Agent--<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>

To this, through the spring AOP intercept exception is completed, this is only to intercept the DAO layer of exception, the advantage of this method is to handle the exception and function to completely separate open, only need to write the method to remember to throw the corresponding exception, when an exception occurs Throwsadvice will intercept the exception, And gets the details of the exception.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.