package org.learn.spring5.service.impl; import org.aspectj.lang.ProceedingJoinPoint; //增强类,编写增强的方法 public class UserServiceProxy { public void before(){ System.out.println("before"); } public void after(){ System.out.println("After"); } public void afterReturning(){ System.out.println("afterReturning"); } public void afterThrowing(){ System.out.println("AfterThrowing"); } public void around(ProceedingJoinPoint proceedingJoinPoint){ System.out.println("环绕之前"); try { proceedingJoinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } System.out.println("环绕之后"); } }
2. 配置XML文件 bean1.xml
1)创建对象
2)配置AOP部分
<?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 https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--Spring AOP操作,基于XML实现方式--> <!--对象创建--> <bean id="userServiceImpl" class="org.learn.spring5.service.impl.UserServiceImpl"></bean> <bean id="userServiceProxy" class="org.learn.spring5.service.impl.UserServiceProxy"></bean> <!-- 配置AOP增强--> <aop:config> <!--切入点--> <aop:pointcut id="p" expression="execution(* org.learn.spring5.service.impl.UserServiceImpl.add(..))"/> <!--配置切面--> <aop:aspect ref="userServiceProxy"> <aop:before method="before" pointcut-ref="p"/> <aop:after method="after" pointcut-ref="p"/> <aop:after-returning method="afterReturning" pointcut-ref="p"/> <aop:after-throwing method="afterThrowing" pointcut-ref="p"/> <aop:around method="around" pointcut-ref="p"/> </aop:aspect> </aop:config> </beans>3. 编写测试类
import org.junit.Test; import org.learn.spring5.service.UserService; import org.learn.spring5.service.impl.UserServiceImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpring5 { /** * Spring AOP实现 基于XML方式 */ @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); UserService userService = context.getBean("userServiceImpl", UserService.class); userService.add(); } }