applicationContext.xml中写法
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 带被功能增强的类 -->
<bean id="person" class="com.cbb.bean.Person"></bean>
<!-- 配置一个切面 -->
<bean id="myAdvice" class="com.cbb.advice.MyAdivice"></bean>
<!-- aop配置 -->
<aop:config>
<!-- aop配置切面 通过ref指向增强的bean切面-->
<aop:aspect ref="myAdvice">
<!-- aop配置切点 可以放到切面里面可以使用这个切点,也可以放在切面外部,代表全局的,所有的切面都可以使用这个切点
expression:写切点表达式-->
<aop:pointcut expression="execution(* com.cbb.bean.*.*(..))" id="myCut"/>
<aop:pointcut expression="execution(String com.cbb.bean.Person.run(String))" id="myCut1"/>
<!-- 配置前通知 method:对应切面的哪个方法 -->
<aop:before method="doBefore" pointcut-ref="myCut"/>
<!-- 配置后通知 method:可以称之为最终通知,无论如何都会执行 -->
<aop:after method="doAfter" pointcut-ref="myCut1"/>
<!-- 配置返回后通知 method:只有正常返回才会执行 -->
<aop:after-returning method="doAfterR" pointcut-ref="myCut1"/>
<!-- 异常通知:程序报错了才通知 -->
<aop:after-throwing method="doThrow" pointcut-ref="myCut1"/>
<!-- 环绕通知 = 前通知+返回后通知 -->
<aop:around method="doAround" pointcut-ref="myCut1"/>
</aop:aspect>
</aop:config>
</beans>
切面类
package com.cbb.advice;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyAdivice {
public void doBefore() {
System.out.println("前通知...");
}
public void doAfter() {
System.out.println("后通知...");
}
public void doAfterR() {
System.out.println("返回后通知...");
}
public void doThrow() {
System.out.println("异常通知...");
}
/**
* @param joinPoint:连接点
* @throws Throwable
*/
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕通知开始...");
Object object = joinPoint.proceed();
System.err.println("环绕通知结束...");
return object;
}
}
Person类,要用切点的类
package com.cbb.bean;
public class Person {
public void eat() {
System.out.println("Chi");
}
public void run() {
System.out.println("Pao");
}
public String run(String name) {
System.out.println(name+"在跑步");
//int a=1/0;
return name;
}
}
测试类
package com.cbb.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cbb.bean.Person;
public class AOPTest {
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person =applicationContext.getBean(Person.class);
person.eat();
String string="sse";
person.run(string);
}
}