Spring学习笔记Day02——AOP
通过第一天的学习知道了Spring的核心有两个:IoC(控制反转)和AOP(面向切面)。IoC可以称为spring容器,用来管理工程下的所有对象,从对象的额创建到销毁的整个生命周期,这些对象被称为spring bean。spring容器使用依赖注入(DI)来管理组成一个应用程序的组件。今天学习spring另一个核心组件AOP。
1.AOP
1.1 什么是AOP?
- 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
- AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码。
- 经典应用:事务管理、性能监视、安全检查、缓存 、日志等。
- Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码。
- AspectJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入。
1.2 AOP实现原理
- aop底层将采用代理机制进行实现。
- 接口 + 实现类 :spring采用 jdk 的动态代理Proxy。
- 实现类:spring 采用 cglib字节码增强。
1.3 AOP 术语
- target:目标类,需要被代理的类。例如:UserService
- Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法
- PointCut 切入点:已经被增强的连接点。例如:addUser()
- advice 通知/增强,增强代码。例如:after、before
- Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.
- proxy 代理类
- Aspect(切面): 是切入点pointcut和通知advice的结合
1.4 AOP通知类型
- AOP联盟为通知Advice定义了org.aopalliance.aop.Advice
- Spring按照通知Advice在目标类方法的连接点位置,可以分为5类
- 前置通知org.springframework.aop.MethodBeforeAdvice
- 在目标方法执行前实施增强
- 后置通知 org.springframework.aop.AfterReturningAdvice
- 在目标方法执行后实施增强
- 环绕通知 org.aopalliance.intercept.MethodInterceptor
- 在目标方法执行前后实施增强
- 异常抛出通知 org.springframework.aop.ThrowsAdvice
- 在方法抛出异常后实施增强
- 引介通知 org.springframework.aop.IntroductionInterceptor
- 在目标类中添加一些新的方法和属性
- 前置通知org.springframework.aop.MethodBeforeAdvice
1.5 看一个例子
在工程里导入spring-framework-3.0.2.RELEASE-dependencies\org.aspectj\com.springsource.org.aspectj.weaver\1.6.8.RELEASE这个包
创建两个目标类IUserService和UserServiceImpl
接口IUserService
public interface IUserService {
public void addUser();
public void updateUser();
public void deleteUser();
}
实现类UserServiceImpl
public class UserServiceImpl implements IUserService {
@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继承MethodInterceptor
/**
* 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
* * 采用“环绕通知” MethodInterceptor
*
*/
public class MyAspect implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
System.out.println("前");
//手动执行目标方法
Object obj = mi.proceed();
System.out.println("后");
return obj;
}
}
然后编写配置文件beans.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">
<!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.hwua.springaopauto.UserServiceImpl"></bean>
<!-- 2 创建切面类 -->
<bean id="myAspectId" class="com.hwua.springaopauto.MyAspect"></bean>
<!-- 3 aop编程
3.1 导入命名空间
3.2 使用 <aop:config>进行配置
proxy-target-class="true" 声明时使用cglib代理
<aop:pointcut> 切入点,从目标对象获得具体方法
<aop:advisor> 特殊的切面,只有一个通知和一个切入点
advice-ref 通知引用
pointcut-ref 切入点引用
3.3 切入点表达式
execution(* com.hwua.springaopauto.*.*(..))
选择方法 返回值任意包类名任意方法名任意参数任意
-->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.hwua.springaopauto.*.*(..))" id="myPointCut"/>
<aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
</aop:config>
</beans>
测试方法
@Test
public void test01() {
String xmlPath = "com/spring/aop/beans.xml";
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
IUserService ius = (IUserService) applicationContext.getBean("userServiceId");
ius.addUser();
}
如果操作正确,上面那个东西的输出结果应该是
前
addUser
后
在addUser上下环绕了前方法和后方法,这就是环绕通知。通过切面给目标类中的方法环绕了前方法和后方法。
2.AspectJ
2.1 AspectJ介绍
- AspectJ是一个基于Java语言的AOP框架
- Spring2.0以后新增了对AspectJ切点表达式支持
- @AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面
新版本Spring框架,建议使用AspectJ方式来开发AOP - 主要用途:自定义开发
2.2 切入点表达式
- execution() 用于描述方法 【掌握】
语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常)
修饰符,一般省略
public 公共方法
* 任意
返回值,不能省略
void 返回没有值
String 返回值字符串
* 任意
包,[省略]
com.hwua.crm 固定包
com.hwua.crm.*.service crm包下面子包任意 (例如:com.hwua.crm.staff.service)
com.hwua.crm.. crm包下面的所有子包(含自己)
com.hwua.crm.*.service.. crm包下面任意子包,固定目录service,service目录任意包
类,[省略]
UserServiceImpl 指定类
*Impl 以Impl结尾
User* 以User开头
* 任意
方法名,不能省略
addUser 固定方法
add* 以add开头
*Do 以Do结尾
* 任意
(参数)
() 无参
(int) 一个整型
(int ,int) 两个
(..) 参数任意
throws ,可省略,一般不写。
综合1
execution(* com.hwua.crm.*.service..*.*(..))
综合2
<aop:pointcut expression="execution(* com.hwua.*WithCommit.*(..)) ||
execution(* com.hwua.*Service.*(..))" id="myPointCut"/>
2.3 AspextJ 通知类型
- aop联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称。
- aspectj 通知类型,只定义类型名称。已经方法格式。
- 个数:6种,知道5种,掌握1中。
- before:前置通知(应用:各种校验)
在方法执行前执行,如果通知抛出异常,阻止方法运行 - afterReturning:后置通知(应用:常规数据处理)
- 方法正常返回后执行,如果方法中抛出异常,通知无法执行
- 必须在方法执行后才执行,所以可以获得方法的返回值。
- around:环绕通知(应用:十分强大,可以做任何事情)
- 方法执行前后分别执行,可以阻止方法的执行
- 必须手动执行目标方法
- afterThrowing:抛出异常通知(应用:包装异常信息)
- 方法抛出异常后执行,如果方法没有抛出异常,无法执行
- after:最终通知(应用:清理现场)
- 方法执行完毕后执行,无论方法中是否出现异常
- before:前置通知(应用:各种校验)
环绕通知的写法
try{
//前置:before
//手动执行目标方法
//后置:afterRetruning
} catch(){
//抛出异常 afterThrowing
} finally{
//最终 after
}
2.3.1 需要导入的jar包
- aop联盟规范 com.springsource.org.aoplliance-1.0.0.jar
- spring aop 实现 com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
- aspect 规范 spring-aop-4.3.15.RELEASE.jar
- spring aspect 实现 spring-aspects-4.3.15.RELEASE.jar
2.3.2 基于xml配置的例子
创建目标类
接口IUserService
public interface IUserService {
public void addUser();
public void updateUser();
public void deleteUser();
}
实现类UserServiceImpl
public class UserServiceImpl implements IUserService {
@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
public class MyAspact {
public void myBefore(JoinPoint joinPoint) {
System.out.println("前置通知 " + joinPoint.getSignature().getName());
}
public void myAfterReturning(JoinPoint joinPoint, Object ret) {
System.out.println("后置通知 " + joinPoint.getSignature().getName() + " , -->" + ret);
}
//环绕通知
public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
try {
System.out.println("前");
result = joinPoint.proceed();
System.out.println("后");
} finally {
System.out.println("最终");
}
return result;
}
}
spring配置文件beans.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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.spring.aspecej.UserServiceImpl"></bean>
<!-- 2 创建切面类 -->
<bean id="myAspectId" class="com.spring.aspecej.MyAspact"></bean>
<!-- 3 aop编程 <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法) ref 切面类引用 <aop:pointcut>
声明一个切入点,所有的通知都可以使用。 expression 切入点表达式 id 名称,用于其它通知引用 -->
<aop:config proxy-target-class="true">
<aop:aspect ref="myAspectId">
<!-- 配置切入点表达式 -->
<aop:pointcut id="myPointCutId"
expression="execution(* com.spring.aspecej.*.*(..))" />
<!-- 前置通知 -->
<aop:before method="myBefore" pointcut-ref="myPointCutId" />
<!-- 后置通知 -->
<!-- <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut"
returning="ret" /> -->
<!-- 环绕通知 -->
<!-- <aop:around method="myAround" pointcut-ref="myPointCut"/> -->
<!-- 异常通知 -->
<!-- <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut"
throwing="e"/> -->
<aop:around method="myAround" pointcut-ref="myPointCutId" />
</aop:aspect>
</aop:config>
</beans>
测试方法
public void test01() {
String xmlPath = "com/spring/aspecej/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
IUserService ius = (IUserService) applicationContext.getBean("userServiceId");
ius.addUser();
ius.deleteUser();
ius.updateUser();
}
输出结果为
前置通知 addUser
前
addUser
后
最终
前置通知 deleteUser
前
deleteUser
后
最终
前置通知 updateUser
前
updateUser
后
最终
2.3.3 基于注解配置的例子
接口IUserService
public interface IUserService {
public void addUser();
public void updateUser();
public void deleteUser();
}
实现类UserServiceImpl
@Service("userServiceId")
public class UserServiceImpl implements IUserService {
@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
@Component("myAspectId")
@Aspect
public class MyAspact {
@Pointcut("execution(* com.spring.aspecej.a.UserServiceImpl.addUser(..))")
private void myPointCut() {
}
public void myBefore(JoinPoint joinPoint) {
System.out.println("前置通知 " + joinPoint.getSignature().getName());
}
public void myAfterReturning(JoinPoint joinPoint, Object ret) {
System.out.println("后置通知 " + joinPoint.getSignature().getName() + " , -->" + ret);
}
@Around("myPointCut()")
public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
try {
System.out.println("前");
result = joinPoint.proceed();
System.out.println("后");
} finally {
System.out.println("最终");
}
return result;
}
}
spring配置文件beans.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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="com.spring.aspecej.a"></context:component-scan>
<!-- 开启AOP注解 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
测试方法
public void test01() {
String xmlPath = "com/spring/aspecej/a/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
IUserService ius = (IUserService) applicationContext.getBean("userServiceId");
ius.addUser();
ius.deleteUser();
ius.updateUser();
}
上面代码的输出结果是
前
addUser
后
最终
deleteUser
updateUser
用注解配置感觉简单了好多,不用陪一大堆配置文件了
2.3.4 aop注解总结
- @Aspect 声明切面,修饰切面类,从而获得 通知。
- 通知
- @Before 前置
- @AfterReturning 后置
- @Around 环绕
- @AfterThrowing 抛出异常
- @After 最终
- 切入点
- @PointCut(“execution(*包名.类名.方法(参数))”),修饰方法 private void xxx(){} 之后通过“方法名”获得切入点引用
- @Component 创建切面类bean,替换
<bean id="myAspectId" class="com.hwua.springaopauto.MyAspect2"></bean> - @Service,创建目标类,替换
<bean id="userServiceId" class="com.hwua.springaopauto.UserServiceImpl"></bean>