首先AOP为Aspect Oriented Programming的缩写,在软件行业开发中的翻译是面向切面编程,通过预编译和动态代理的方式实现程序统一维护的一种方式,同时它也是对OOP(面向对象)的一种延续。利用AOP可以实现对业务代码的隔离,从而使得业务之间的耦合性降低。提高软件的开发效率和一些程序的可用性!
将日志管理 ,性能统计,安全控制,异常记录等从代码中分离出来,对这些行为的分离,我们希望他们可以分离到非业务逻辑的代码中去,进而改变这些代码影响业务逻辑代码!
使用AOP织入,需要导入一个依赖包
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency>通过Spring AoI实现 首先来编写业务接口和实现类 业务接口
实现类
编写两个增强类,编写两个 一个前置增强,一个后置增强
编写配置文件
<?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--> <bean id="userService" class="com.jie.service.UserServiceImpl"/> <bean id="log" class="com.jie.log.Log"/> <bean id="afterLog" class="com.jie.log.AfterLog"/> <!-- Aop配置--> <aop:config> <!-- 切入点 expression:表达式要执行的方法--> <aop:pointcut id="pointcut" expression="execution(* com.jie.service.UserServiceImpl.*(..))"/> <!-- 执行环绕;advice-ref执行方法,pointcut-ref切入点--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> </beans>编写测试及其结果
写入一个自己写的切入类
去spring中配置
测试结果
编写配置文件
测试结果
