起始对象(main 程序开始 发送请求)
目标对象(Target Object)
切面对象(Aspect)
代理对象(AOP Proxy Spring容器帮我们创建的 用来管理切面对象)
切点(切入点 Pointcut 目标对象中的方法 目标 切面-观察 目标做了件感兴趣的事情 观察者就动)
连接点(Join Point 切面对象中的方法)
建议/通知(advice 连接点中执行时的过程)
前置 before
后置 after-returning
异常 after-throwing
最终 after
环绕 around
TestMain
package test;
import controller.TestController;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain {
public static void main(String[] args){
//调用controller中的test方法
BeanFactory factory=new ClassPathXmlApplicationContext("ApplicationContext.xml");
//1.需要一个controller对象---IOC管理对象
TestController controller=(TestController) factory.getBean("controller");
//2.调用方法
controller.test();
}
}
TestController
package controller;
/**
* 这是一个Controller
* 可以理解为是之前的Servlet(以后发送请求访问的那个目标对象)
*/
public class TestController {
public void test() {
System.out.println("目标方法");
}
}
Aspect1
package aspect;
/**
* 这是一个切面对象
*/
public class Aspect1 {
//切面对象中的方法本身叫做连接点
//方法什么时候(最终目标之前、之后......)执行方式 建议
public void beforeMethod(){
System.out.println("前置1");
}
public void afterReturningMethod(){
System.out.println("后置1");
}
public void after(){
System.out.println("最终1");
}
}
Aspect2
package aspect;
/**
* 这是一个切面对象
*/
public class Aspect2 {
//切面对象中的方法本身叫做连接点
//方法什么时候(最终目标之前、之后......)执行方式 建议
public void beforeMethod(){
System.out.println("前置2");
}
public void afterReturningMethod(){
System.out.println("后置2");
}
}
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation=" http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd "
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns="http://www.springframework.org/schema/beans">
<bean id="controller" class="controller.TestController"></bean>
<bean id="aspect1" class="aspect.Aspect1"></bean>
<bean id="aspect2" class="aspect.Aspect2"></bean>
<!--给切面对象做一个说明-->
<aop:config>
<!--需要说明哪一些对象是切面对象-->
<aop:aspect id="as1" ref="aspect1">
<!--说明切点 目标对象中的方法-->
<!--expression 包 类 方法-->
<aop:pointcut id="mycut" expression="execution(* controller.TestController.test())"/>
<!--切面对象做的建议方式(连接点的执行 连接点是切面中的方法)-->
<aop:before method="beforeMethod" pointcut-ref="mycut"></aop:before>
<aop:after-returning method="afterReturningMethod" pointcut-ref="mycut"></aop:after-returning>
<aop:after method="after" pointcut-ref="mycut"></aop:after>
</aop:aspect>
<aop:aspect id="as2" ref="aspect2">
<!--说明切点 目标对象中的方法-->
<!--expression 包 类 方法-->
<aop:pointcut id="mycut" expression="execution(* controller.TestController.test())"/>
<!--切面对象做的建议方式(连接点的执行 连接点是切面中的方法)-->
<aop:before method="beforeMethod" pointcut-ref="mycut"></aop:before>
<aop:after-returning method="afterReturningMethod" pointcut-ref="mycut"></aop:after-returning>
</aop:aspect>
</aop:config>
</beans>