AOP的实现方式
在实现之前我们需要导入AOP的织入包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
1.第一种方式
通过spring 的API接口 实现
首先编写业务接口和实现类
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void select() {
System.out.println("查找了一个用户");
}
}
接着再写增强类,前置增强和后置增强
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
//method:要执行目标对象的方法
//args:参数
//target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
//method:要执行目标对象的方法
//args:参数
//target:目标对象
// returnValue:返回值
public void afterReturning
(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println
(target.getClass().getName()+"的"+method.getName()+"被执行了,并返回"+returnValue);
}
}
最后去spring的文件中注册,实现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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/beans/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.ni.service.UserService"/>
<bean id="log" class="com.ni.Log.Log"/>
<bean id="afterLog" class="com.ni.Log.AfterLog"/>
<!--方式一:使用原生spring API接口-->
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点 expression:表达式 execution(要执行的位置 * * * * *)-->
<aop:pointcut id="pointcut" expression="execution(com.ni.service.UserServiceImpl.*(....))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .