applicationContext.xml
- 切点标签、切点对象
- 通知标签、通知对象
- aspectJ方式是自己定义方法,通知标签只指明了通知类中的方法名,然后还要在aspect标签上写通知类的类名
- schema-based是固定的方法,异常通知类中的方法名必须为afterThrowing,所以通知标签中指明通知类即可
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="mythrow" class="cn.wit.advice.MyThrow"></bean>
<aop:config>
<aop:pointcut expression="execution(* cn.wit.test.Demo.Demo1())" id="mypoint"/>
<aop:advisor advice-ref="mythrow" pointcut-ref="mypoint"/>
</aop:config>
<bean id="demo" class="cn.wit.test.Demo"></bean>
</beans>
异常通知类
方法名必须为afterThrowing
public class MyThrow implements ThrowsAdvice{
public void afterThrowing(Exception ex) throws Throwable{
System.out.println("异常通知");
}
}
Demo类
public class Demo {
public void Demo1(){
int i=5/0;
System.out.println("demo1");
}
public void Demo2(){
System.out.println("demo2");
}
public void Demo3(){
System.out.println("demo3");
}
}
测试
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Demo demo = ac.getBean("demo",Demo.class);
try {
demo.Demo1();
} catch (Exception e) {
}
}
}