/**
* 这是一个切面对象
*/
public class Aspect1 {
//切面对象中的分方法本身叫连接点
//方法什么时候(最终目标之前 之后 。。)执行方式 建议
public void beforeMethod(){
System.out.println("预备 开始 喊~~~");
}
public void afterReturningMethod(){
System.out.println("请坐");
}
public void afterThrowingMethod(){
System.out.println("出现异常啦");
}
public void afterMethod(){
System.out.println("最终我很开心");
}
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {//特别像是以前的Filter 放行 底层责任链实现方式
System.out.println("环绕建议前部分");
//中间等待目标执行完
pjp.proceed();//chain.doFilter();
System.out.println("环绕建议后部分");
}
}
TestController
/**
* 这是一个Controller
* 可以理解为是之前的Servlet(以后发送请求访问的那个目标对象)
*/
public class TestController {
public void test(){
System.out.println("阿拓老师很帅!!!");
}
}
TestMain
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();//目标方法
/*
try{
前置
环绕前
目标方法(环绕的是目标的前后)
环绕后
后置
}catch(){
异常
}finally{
最终
}
*/
}
}
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<bean id="controller" class="controller.TestController"></bean>
<bean id="aspect1" class="aspect.Aspect1"></bean>
<bean id="aspect2" class="aspect.Aspect2"></bean>
<!--给切面对象做一个说明-->
<aop:config>
<!--需要说明哪一个 哪一些对象是切面对象-->
<aop:pointcut id="mycut" expression="execution(* controller.TestController.test())"></aop:pointcut>
<aop:aspect id="as1" ref="aspect1">
<!--说明切点 目标对象中的方法-->
<!--expression 包 类 方法-->
<!--切面对象做的建议方式(连接点的执行 连接点是切面中的方法)-->
<aop:before method="beforeMethod" pointcut-ref="mycut"></aop:before>
<aop:around method="aroundMethod" pointcut-ref="mycut"></aop:around>
<aop:after-returning method="afterReturningMethod" pointcut-ref="mycut"></aop:after-returning>
<aop:after-throwing method="afterThrowingMethod" pointcut-ref="mycut"></aop:after-throwing>
<aop:after method="afterMethod" pointcut-ref="mycut"></aop:after>
</aop:aspect>
<!--第二个切面对象-->
<aop:aspect id="as2" ref="aspect2">
<aop:pointcut id="mycut" expression="execution(* controller.TestController.test())"></aop:pointcut>
<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>
网友评论