AOP概念
面向切面编程(也叫面向方面编程):Aspect Oriented Programming(AOP),是软件开发中的一个热点,也是Spring框架中的一个重要内容。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP是OOP的延续。
主要的功能是:日志记录,性能统计,安全控制,事务处理,异常处理等等。
主要的意图是:将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。
可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。AOP实际是GoF设计模式的延续,设计模式孜孜不倦追求的是调用者和被调用者之间的解耦,提高代码的灵活性和可扩展性,AOP可以说也是这种目标的一种实现。
在Spring中提供了面向切面编程的丰富支持,允许通过分离应用的业务逻辑与系统级服务(例如审计(auditing)和事务(transaction)管理)进行内聚性的开发。应用对象只实现它们应该做的——完成业务逻辑——仅此而已。它们并不负责(甚至是意识)其它的系统级关注点,例如日志或事务支持。1.简介
AOP主要包含了通知、切点和连接点等术语,介绍如下
-
通知(Advice)
通知定义了切面是什么以及何时调用,何时调用包含以下几种Before 在方法被调用之前调用通知
After 在方法完成之后调用通知,无论方法执行是否成功
After-returning 在方法成功执行之后调用通知
After-throwing 在方法抛出异常后调用通知
Around 通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为 -
切点(PointCut)
通知定义了切面的什么和何时,切点定义了何处,切点的定义会匹配通知所要织入的一个或多个连接点,我们通常使用明确的类的方法名称来指定这些切点,或是利用正则表达式定义匹配的类和方法名称来指定这些切点。
切点的格式如下execution(* com.ganji.demo.service.user.UserService.GetDemoUser (..) )
-
连接点(JoinPoint)
连接点是在应用执行过程中能够插入切面的一个点,这个点可以是调用方法时,抛出异常时,甚至是修改一个字段时,切面代码可以利用这些连接点插入到应用的正常流程中,并添加新的行为,如日志、安全、事务、缓存等。
现阶段的AOP框架
AOP框架除了Spring AOP之外,还包括AspectJ、JBoss AOP;
上述框架的区别是Spring AOP只支持到方法连接点,另外两个还支持字段和构造器连接点。
2.应用
需要spring的核心包外,还需要aspectjrt.jar、aspectjweaver.ja、cglib-nodep.jar几个包
第一种实现的方式:通过Spring的API实现AOP。
public interface UserService {
public void add();
public void update(int a);
public void delete();
public void search();
}
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("增加用户");
}
@Override
public void update(int a) {
System.out.println("修改用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
@Override
public void search() {
System.out.println("查询用户");
}
public class Log implements MethodBeforeAdvice{
/**
* @param method 被调用方法对象
* @param args 被调用的方法的参数
* @param target 被调用的方法的目标对象
* */
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"方法被执行");
}
}
<?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="userService" class="com.spring.service.impl.UserServiceImpl"/>
<!-- 这个切面也要配置成bean-->
<bean id="log" class="com.spring.advice.Log"/>
<aop:config>
<!--切入点,需要告诉方法在什么去执行
expression="execution(* com.spring.service.impl.*.*(..))"
第一个* 表示所有的返回值,然后就是包名
第二个*表示所有的类对象
第三个*表示类对象所有的方法
第四个..表示所有方法下面的带参数的方法或者是不带参数的方法
-->
<aop:pointcut expression="execution(* com.spring.service.impl.*.*(..))" id="pointcut"/>
<!-- 在所有的方法中都切入前置通知-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
</aop:config>
</beans>
package com.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.service.UserService;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService)ac.getBean("userService");
userService.update(2);
userService.add();
}
}
三月 12, 2017 2:22:44 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@439f5b3d: startup date [Sun Mar 12 14:22:44 GMT+08:00 2017]; root of context hierarchy
三月 12, 2017 2:22:44 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
com.spring.service.impl.UserServiceImpl的update方法被执行
修改用户
com.spring.service.impl.UserServiceImpl的add方法被执行
增加用户
public class AfterLog implements AfterReturningAdvice{
/**
* 目标方法执行后执行的通知
* returnValue--返回值
* method 被调用的方法对象
* args 被调用的方法对象的参数
* target 被调用的方法对象的目标对象
* */
@Override
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被成功执行,返回值是:"+returnValue);
}
}
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class ExceptionLog implements ThrowsAdvice {
public void afterThrowing(Method method,Exception ex) throws Throwable {
}
}
<!-- 这个切面也要配置成bean-->
<bean id="log" class="com.spring.advice.Log"/>
<bean id="afterLog" class="com.spring.advice.AfterLog"></bean>
<aop:config>
<!--切入点,需要告诉方法在什么去执行
expression="execution(* com.spring.service.impl.*.*(..))"
第一个* 表示所有的返回值,然后就是包名
第二个*表示所有的类对象
第三个*表示类对象所有的方法
第四个..表示所有方法下面的带参数的方法或者是不带参数的方法
-->
<aop:pointcut expression="execution(* com.spring.service.impl.*.*(..))" id="pointcut"/>
<!-- 在所有的方法中都切入前置通知-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
三月 12, 2017 2:28:19 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@439f5b3d: startup date [Sun Mar 12 14:28:19 GMT+08:00 2017]; root of context hierarchy
三月 12, 2017 2:28:19 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
com.spring.service.impl.UserServiceImpl的update方法被执行
修改用户
com.spring.service.impl.UserServiceImpl的update被成功执行,返回值是:null
com.spring.service.impl.UserServiceImpl的add方法被执行
增加用户
com.spring.service.impl.UserServiceImpl的add被成功执行,返回值是:null
public class Log {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
<?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="userService" class="com.spring.service.impl.UserServiceImpl"/>
<!-- 这个切面也要配置成bean-->
<bean id="log" class="com.spring.advice.Log"/>
<aop:config>
<!--切入点,需要告诉方法在什么去执行
expression="execution(* com.spring.service.impl.*.*(..))"
第一个* 表示所有的返回值,然后就是包名
第二个*表示所有的类对象
第三个*表示类对象所有的方法
第四个..表示所有方法下面的带参数的方法或者是不带参数的方法
-->
<aop:aspect ref="log">
<aop:pointcut expression="execution(* com.spring.service.impl.*.*(..))" id="pointcut"/>
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
package com.spring.advice;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.aop.MethodBeforeAdvice;
@Aspect
public class Log {
@Before("execution(* com.spring.service.impl.*.*(..))")
public void before(){
System.out.println("方法执行前");
}
@After("execution(* com.spring.service.impl.*.*(..))")
public void after(){
System.out.println("方法执行后");
}
@Around("execution(* com.spring.service.impl.*.*(..))")
public Object around(ProceedingJoinPoint jp) throws Throwable{
System.out.println("环绕前");
System.out.println("方法"+jp.getSignature());
Object result=jp.proceed();
System.out.println("环绕后");
return result;
}
}
<?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="userService" class="com.spring.service.impl.UserServiceImpl"/>
<!-- 这个切面也要配置成bean-->
<bean id="log" class="com.spring.advice.Log"/>
<aop:aspectj-autoproxy/>
</beans>
三月 12, 2017 3:00:02 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@439f5b3d: startup date [Sun Mar 12 15:00:02 GMT+08:00 2017]; root of context hierarchy
三月 12, 2017 3:00:02 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
环绕前
方法void com.spring.service.UserService.update(int)
方法执行前
修改用户
环绕后
方法执行后