AOP是面向切面编程,其思想是基于静态代理和动态代理的。一个程序的编写是从上往下的,如果后期维护和添加功能,按平常的方式需要不停的修改代码,这是不可取的,所以面向切面编程是对代码横向的拓展,在不需要修改原有代码的基础上,对代码进行维护和拓展。
首先需要导包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.11</version>
</dependency>
一个接口
public interface userdao {
void add();
void delete();
}
接口的实现类
package com.xzr.demo.spring.aop;
public class userService implements userdao{
@Override
public void add() {
System.out.println("增加用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
}
一个功能如果要添加代码,那就是在代码前或后面添加,新建一个执行前的方法继承aop的MethodBeforeAdvice
public class log implements MethodBeforeAdvice {
//method:要执行的目标方法
//objects:参数
//o:目标对象
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(
o.getClass().getName() +"的"+method.getName()+"被执行"
);
}
}
新建一个执行后的方法继承aop的AfterReturningAdvice
public class logAfter implements AfterReturningAdvice {
//拿到了返回值
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+"返回的结果"+o);
}
}
编写applicationContext.xml
pointCut:切点,就是要拓展的那段代码
<?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-aop.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="com.xzr.demo.spring.aop.userService"/>
<bean id="log" class="com.xzr.demo.spring.aop.log"></bean>
<bean id="logAfter" class="com.xzr.demo.spring.aop.logAfter"></bean>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.xzr.demo.spring.aop.userService.*(..))"/>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="logAfter" pointcut-ref="pointcut"/>
</aop:config>
</beans>
main方法
public class me {
public static void main(String[] args) {
ApplicationContext cont = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理返回的是接口
userdao userService = cont.getBean("userService", userdao.class);
userService.add();
}
}
执行后的结果就是你懂的,add方法被前后添加新的方法了。然后这新的就是方法又是全部了,反正原理就是动态代理,灰常重要,也能用注解实现的。