异常抛出增强的特点是在目标方法抛出异常时织入增强处理。
注意:ThrowsAdvice接口中并没有定义任何方法,但是我们在定义异常抛出的增强方法时必须遵守以下方法签名。
void afterThrowing(Method method,Object[] args, Object target, RuntimeException e)
1.首先人为制造一个异常,
1 package com.dao.impl; 2 3 import com.dao.IUserDao; 4 import com.domain.User; 5 6 public class IUserDaoImpl implements IUserDao { 7 8 @Override 9 public void save(User user) { 10 // TODO Auto-generated method stub 11 System.out.println("哇塞,保存用户信息了"); 12 //故意制造异常 13 throw new RuntimeException("看到这个别紧张,是故意制造的异常"); 14 } 15 16 }
2.写个异常处理类
1 package com.aop; 2 3 import java.sql.SQLException; 4 import java.lang.reflect.Method; 5 import org.apache.log4j.Logger; 6 import org.springframework.aop.ThrowsAdvice; 7 8 public class ErrorLogger implements ThrowsAdvice { 9 10 private static final Logger log = Logger.getLogger(ErrorLogger.class); 11 12 public void afterThrowing(Method method,Object[] args, Object target, RuntimeException e){ 13 log.error(method.getName()+"方法发生异常:"+e); 14 } 15 public void afterThrowing(Method method,Object[] args, Object target, SQLException ex){ 16 log.error(method.getName()+"方法发生异常:"+ex); 17 } 18 }
3.配置spring配置文件,记得到aop空间
1 <bean id="dao" class="com.dao.impl.IUserDaoImpl"></bean> 2 <bean id="biz" class="com.biz.impl.IUserBizImpl"> 3 <property name="dao" ref="dao"></property> 4 </bean> 5 <bean id="errorlog" class="com.aop.ErrorLogger"></bean> 6 <aop:config> 7 <!-- <aop:pointcut expression="execution(public void save(com.domain.User))" id="pointcut"/>--> 8 <aop:pointcut expression="execution(* com.biz.IUserBiz.*(..))" id="pointcut"/> 9 <aop:advisor advice-ref="errorlog" pointcut-ref="pointcut"/> 10 </aop:config>
4.编写测试类
1 package com.test; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 import com.biz.IUserBiz; 6 import com.domain.User; 7 8 /** 9 * 10 * @author Mr 11 * aop测试类 12 */ 13 public class Test { 14 15 public static void main(String[] args) { 16 //解析配置文件 17 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); 18 19 IUserBiz biz = (IUserBiz) ac.getBean("biz"); 20 User user = new User(); 21 user.setUname("小老虎"); 22 biz.save(user); 23 } 24 25 }
5.测试效果