//配置文件部分
<aop:config>
<aop:aspect ref="aopUtil">
<aop:pointcut expression="execution(* com.pojo.*.*(..))" id="pointcut"/>
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after-returning method="beforeReturn" pointcut-ref="pointcut" returning="result"/>
<aop:after method="after" pointcut-ref="pointcut"/>
<aop:around method="around" pointcut-ref="pointcut"/>
<aop:after-throwing method="testException" pointcut-ref="pointcut" throwing="ex"/>
</aop:aspect>
</aop:config>
//java bean部分
package com.aop;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
public class aopUtil {
public static Logger log = Logger.getLogger(aopUtil.class);
public void before(JoinPoint jp){
System.out.println("方法对象为:----"+jp.getTarget()+"方法名为:----"+jp.getSignature());
}
public void beforeReturn(JoinPoint jp,Object result){
System.out.println("输出结果为:----"+result);
}
public void after(JoinPoint jp){
System.out.println("方法执行完毕");
}
public Object around(ProceedingJoinPoint pjp) throws Throwable{
Object obj=null;
try {
obj=pjp.proceed();
log.debug("环绕开始!");
log.debug("方法对象为:----"+pjp.getTarget()+"方法名为:----"+pjp.getSignature());
} catch (Exception e) {
log.debug("环绕捕捉到了一个异常");
e.printStackTrace();
// TODO: handle exception
}finally{
log.debug("环绕结束");
}
return obj;
}
public void testException(JoinPoint jp,Exception ex){
log.debug("方法对象为:----"+jp.getTarget()+"方法名为:----"+jp.getSignature().getName()+"出现了异常");
}
}
//建一个学生类进行测试
public class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//写一个测试异常的方法,方法里面直接抛出一个异常
public void testException(){
throw new RuntimeException("运行异常");
}
//写一个测试类
package com.test;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.pojo.Student;
public class juntTest {
@Test
public void test() {
ApplicationContext act = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Student stu = (Student)act.getBean("student");
Logger logger= Logger.getLogger(juntTest.class);
logger.debug(stu.getName());
stu.testException();
}
}
输出结果:
异常的测试结果: