等风来,不如追风去!
说明;
和 方式一 的service,serviceimpl相同,不在重复:
同样的, 先写一个方法拦截器的实现类,和方法三相同
package com.qianfeng.aop04;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* Created by Administrator on 2020/3/1.
*/
public class MyAscept implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("------before------");
Object o = methodInvocation.proceed();
System.out.println("------after------");
return null;
}
}
在配置配置文件
<?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">
<!--注意以上添加了三处aop-->
<bean id="us" class="com.qianfeng.aop04.UserServiceImpl"></bean>
<bean id="ma" class="com.qianfeng.aop04.MyAscept"></bean>
<!--proxy-target-class="true"表示强制使用cglig方式来实现动态代理-->
<aop:config proxy-target-class="true">
<!--
定义一个aop切点,实现每个方法的代理
第一个*表示方法的返回值,表示要代理的方法的返回值,如只代理返回值类型是boolean类型的方法时:
<aop:pointcut id="pt" expression="execution(boolean com.qianfeng.aop04.*.*(..))"></aop:pointcut>
如只代理参数列表是int
<aop:pointcut id="pt" expression="execution(* com.qianfeng.aop04.*.*(int))"></aop:pointcut>
-->
<aop:pointcut id="pt" expression="execution(* com.qianfeng.aop04.*.*(..))"></aop:pointcut>
<!--
将MyAscept与切点关联起来
-->
<aop:advisor advice-ref="ma" pointcut-ref="pt"></aop:advisor>
</aop:config>
</beans>
测试类:
package com.qianfeng.aop04;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* Created by Administrator on 2020/3/1.添加一个依赖
* <p>
* 注意:使用此方法的时候用到通配时必须要
*/
public class TestAop04 {
@Test
public void test() {
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("F:\\testmaven\\src\\main\\java\\com\\qianfeng\\aop04\\beans.xml");
IUserService iUserService = applicationContext.getBean("us", IUserService.class);
iUserService.deleteUser(001);
iUserService.getAllUser();
iUserService.saveUser(new Object());
iUserService.updateUser(new Object());
}
}
~over