首先,我们先写一个Service
上代码:接口省略
package com.study.spring_aop;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("addUser...");
}
@Override
public void updateUser() {
System.out.println("updateUser...");
}
@Override
public void deleteUser() {
System.out.println("deleteUser...");
}
}
然后我们再来个简单的切面类myAspect (只写了方法前后打印)
代码:
package com.study.spring_aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
System.out.println("前");
Object object = mi.proceed();
System.out.println("后");
return object;
}
}
配置文件applicationContext.xml(只是在包内的)
<?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">
<!-- 创建目标类 -->
<bean id="userServiceId" class="com.study.spring_aop.UserServiceImpl"></bean>
<!-- 创建切面类 -->
<bean id="myAspectId" class="com.study.spring_aop.MyAspect"></bean>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.study.spring_aop.*.*(..))" id="myPointCut"/>
<aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
</aop:config>
</beans>
解释一下配置文件的一些意思:
使用进行aop配置
proxy-target-class=”true” 声明使用cglib代理 默认是false(jdk代理)
切入点,从目标对象获得具体方法
特殊的切面,只有一个通知和一个引用
pointcut-ref :切入点引用
advice-ref :通知引用
expression:切入点表达式 :execution(* com.study.spring_aop..(..))
选择方法 返回值 包 类任意 方法任意 参数任意
测试类:
package com.study.spring_aop;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpringAop {
@Test
public void demo1(){
String xmlPath = "com/study/spring_aop/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//获得的是目标类
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
userService.deleteUser();
userService.updateUser();
}
}