什么是AOP

为什么需要AOP

  从Spring的角度看,AOP最大的用途就在于提供了事务管理的能力。事务管理就是一个关注点,你的正事就是去访问数据库,而你不想管事务(太烦),所以,Spring在你访问数据库之前,自动帮你开启事务,当你访问数据库结束之后,自动帮你提交/回滚事务!

AOP思想介绍 

  aop底层将采用代理机制进行实现。

  接口 + 实现类时 :spring采用 jdk的动态代理 Proxy。

  只有实现类时:spring 采用cglib字节码增强。

Spring实现AOP的原理

1.jdk动态代理(优先)

  缺点是被代理对象必须要实现接口,才能产生代理对象.如果没有接口将不能使用动态代理技术。

2.cglib代理(没有接口)

  第三方代理技术,cglib代理.可以对任何类生成代理.代理的原理是对目标对象进行继承代理. 如果目标对象被final修饰.那么该类无法被cglib代理.

代码示例

UserService.java

package cn.mf.service;

public interface UserService {
void save();
void delete();
void update();
void find();
}

UserServiceImpl.java

package cn.mf.service;

public class UserServiceImpl implements UserService {
@Override
public void save() {
System.out.println("保存用户!");
//int i = 1/0;
}
@Override
public void delete() {
System.out.println("删除用户!");
}
@Override
public void update() {
System.out.println("更新用户!");
}
@Override
public void find() {
System.out.println("查找用户!");
}
}

动态代理

package cn.mf.c_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import cn.mf.service.UserService;
import cn.mf.service.UserServiceImpl;
//观光代码=>动态代理
public class UserServiceProxyFactory implements InvocationHandler { public UserServiceProxyFactory(UserService us) {
super();
this.us = us;
} private UserService us; public UserService getUserServiceProxy(){
//生成动态代理
UserService usProxy = (UserService) Proxy.newProxyInstance(UserServiceProxyFactory.class.getClassLoader(),
UserServiceImpl.class.getInterfaces(),
this);
//返回
return usProxy;
} @Override
public Object invoke(Object arg0, Method method, Object[] arg2) throws Throwable {
System.out.println("打开事务!");
Object invoke = method.invoke(us, arg2);
System.out.println("提交事务!");
return invoke;
} }

cglib代理

package cn.mf.c_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy; import cn.mf.service.UserService;
import cn.mf.service.UserServiceImpl; //观光代码=>cglib代理
public class UserServiceProxyFactory2 implements MethodInterceptor { public UserService getUserServiceProxy(){
Enhancer en = new Enhancer();//帮我们生成代理对象
en.setSuperclass(UserServiceImpl.class);//设置对谁进行代理
en.setCallback(this);//代理要做什么
UserService us = (UserService) en.create();//创建代理对象
return us;
} @Override
public Object intercept(Object prxoyobj, Method method, Object[] arg, MethodProxy methodProxy) throws Throwable {
//打开事务
System.out.println("打开事务!");
//调用原有方法
Object returnValue = methodProxy.invokeSuper(prxoyobj, arg);
//提交事务
System.out.println("提交事务!");
return returnValue;
}
}

Junit测试

package cn.mf.c_proxy;

import org.junit.Test;

import cn.mf.service.UserService;
import cn.mf.service.UserServiceImpl; public class Demo { @Test
//动态代理
public void fun1(){
UserService us = new UserServiceImpl();
UserServiceProxyFactory factory = new UserServiceProxyFactory(us);
UserService usProxy = factory.getUserServiceProxy();
usProxy.save();
//代理对象与被代理对象实现了相同的接口
//代理对象 与 被代理对象没有继承关系
System.out.println(usProxy instanceof UserServiceImpl );//false
} @Test
public void fun2(){
UserServiceProxyFactory2 factory = new UserServiceProxyFactory2();
UserService usProxy = factory.getUserServiceProxy();
usProxy.save();
//判断代理对象是否属于被代理对象类型
//代理对象继承了被代理对象=>true
System.out.println(usProxy instanceof UserServiceImpl );//true
}
}

AOP术语

•连接点( join point )

  对应的是具体被拦截的对象,因为 Spring 只能支持方法,所以被拦截的对象往往就是指特定的方法,例如,我们前面提到的HelloServiceimpl的sayHello方法就是一个连接点,AOP将通过动态代理技术把它织入对应的流程中。

•切点(point cut)

  有时候,我们的切面不单单应用于单个方法,也可能是多个类的不同方法,这时,可以通过正则式和指示器的规则去定义,从而适配连接点 。 切点就是提供这样一个功能的概念 。

•通知(advice)  

  就是按照约定的流程下的方法,分为前置通知(before advice)、后置通知(afteradvice)、环绕通知(around advice)、事后返回通知(afterRetuming advice)和异常通知(afterThrowing advice ),它会根据约定织入流程中,需要弄明白它们在流程中的顺序和运行的条件。

•目标对象(target)

  即被代理对象,例如,约定编程中的HelloServicelmpl实例就是一个目标对象,它被代理了。

•引入( introduction )

  是指引入新的类和其方法,增强现有 Bean 的功能。

•织入( weaving )

  它是一个通过动态代理技术,为原有服务对象生成代理对象 , 然后将与切点定义匹配的连接点拦截,并按约定将各类通知织入约定流程的过程。

•切面( aspect)

  是一个可以定义切点、各类通知和引入的内容,SpringAOP 将通过它的信息来增强 Bean 的功能或者将对应的方法织入流程 。

Spring中的AOP代码实战之xml配置

1.导包4+2

1)spring的aop包

spring-aspects-4.2.4.RELEASE.jar

spring-aop-4.2.4.RELEASE.jar

2)spring需要第三方aop包

com.springsource.org.aopalliance-1.0.0.jar

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

2.准备目标对象

UserService.java

package cn.mf.service;

public interface UserService {
void save();
void delete();
void update();
void find();
}

UserServiceImpl.java

package cn.mf.service;

public class UserServiceImpl implements UserService {
@Override
public void save() {
System.out.println("保存用户!");
//int i = 1/0;
}
@Override
public void delete() {
System.out.println("删除用户!");
}
@Override
public void update() {
System.out.println("更新用户!");
}
@Override
public void find() {
System.out.println("查找用户!");
}
}

3.准备通知

MyAdvice.java

package cn.mf.d_springaop;

import org.aspectj.lang.ProceedingJoinPoint;

//通知类
public class MyAdvice { //前置通知
// |-目标方法运行之前调用
//后置通知(如果出现异常不会调用)
// |-在目标方法运行之后调用
//环绕通知
// |-在目标方法之前和之后都调用
//异常拦截通知
// |-如果出现异常,就会调用
//后置通知(无论是否出现 异常都会调用)
// |-在目标方法运行之后调用
//----------------------------------------------------------------
//前置通知
public void before(){
System.out.println("这是前置通知!!");
}
//后置通知
public void afterReturning(){
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//环绕通知
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("这是环绕通知之前的部分!!");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("这是环绕通知之后的部分!!");
return proceed;
}
//异常通知
public void afterException(){
System.out.println("出事啦!出现异常了!!");
}
//后置通知
public void after(){
System.out.println("这是后置通知(出现异常也会调用)!!");
}
}

4.配置进行织入,将通知织入目标对象中

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd "> <!-- 准备工作: 导入aop(约束)命名空间 -->
<!-- 1.配置目标对象 -->
<bean name="userService" class="cn.mf.service.UserServiceImpl" ></bean>
<!-- 2.配置通知对象 -->
<bean name="myAdvice" class="cn.mf.d_springaop.MyAdvice" ></bean>
<!-- 3.配置将通知织入目标对象 -->
<aop:config>
<!-- 配置切入点
public void cn.itcast.service.UserServiceImpl.save()
void cn.itcast.service.UserServiceImpl.save()
* cn.itcast.service.UserServiceImpl.save()
* cn.itcast.service.UserServiceImpl.*() * cn.itcast.service.*ServiceImpl.*(..)
* cn.itcast.service..*ServiceImpl.*(..)
-->
<aop:pointcut expression="execution(* cn.mf.service.*ServiceImpl.*(..))" id="pc"/>
<aop:aspect ref="myAdvice" >
<!-- 指定名为before方法作为前置通知 -->
<aop:before method="before" pointcut-ref="pc" />
<!-- 后置 -->
<aop:after-returning method="afterReturning" pointcut-ref="pc" />
<!-- 环绕通知 -->
<aop:around method="around" pointcut-ref="pc" />
<!-- 异常拦截通知 -->
<aop:after-throwing method="afterException" pointcut-ref="pc"/>
<!-- 后置 -->
<aop:after method="after" pointcut-ref="pc"/>
</aop:aspect>
</aop:config>
</beans>

Spring中的AOP代码实战之注解配置

1.导包4+2

2.准备目标对象

3.准备通知

MyAdvice.java

package cn.mf.e_annotationaop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut; //通知类
@Aspect
//表示该类是一个通知类
public class MyAdvice {
@Pointcut("execution(* cn.mf.service.*ServiceImpl.*(..))")
public void pc(){}
//前置通知
//指定该方法是前置通知,并制定切入点
@Before("MyAdvice.pc()")
public void before(){
System.out.println("这是前置通知!!");
}
//后置通知
@AfterReturning("execution(* cn.mf.service.*ServiceImpl.*(..))")
public void afterReturning(){
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//环绕通知
@Around("execution(* cn.mf.service.*ServiceImpl.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("这是环绕通知之前的部分!!");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("这是环绕通知之后的部分!!");
return proceed;
}
//异常通知
@AfterThrowing("execution(* cn.mf.service.*ServiceImpl.*(..))")
public void afterException(){
System.out.println("出事啦!出现异常了!!");
}
//后置通知
@After("execution(* cn.mf.service.*ServiceImpl.*(..))")
public void after(){
System.out.println("这是后置通知(出现异常也会调用)!!");
}
}

4.配置进行织入,将通知织入目标对象中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd "> <!-- 准备工作: 导入aop(约束)命名空间 -->
<!-- 1.配置目标对象 -->
<bean name="userService" class="cn.mf.service.UserServiceImpl" ></bean>
<!-- 2.配置通知对象 -->
<bean name="myAdvice" class="cn.mf.e_annotationaop.MyAdvice" ></bean>
<!-- 3.开启使用注解完成织入 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>

Junit测试

package cn.mf.e_annotationaop;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.mf.bean.User;
import cn.mf.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:cn/mf/e_annotationaop/applicationContext.xml")
public class Demo {
@Resource(name="userService")
private UserService us; @Test
public void fun1(){
us.save();
} }

https://www.cnblogs.com/chenmingjun/p/9413977.html

spring框架学习(四)AOP思想的更多相关文章

  1. spring框架学习(四)——注解方式AOP

    注解配置业务类 使用@Component("s") 注解ProductService 类 package com.how2java.service; import org.spri ...

  2. Spring框架系列之AOP思想

    微信公众号:compassblog 欢迎关注.转发,互相学习,共同进步! 有任何问题,请后台留言联系! 1.AOP概述 (1).什么是 AOP AOP 为 Aspect Oriented Progra ...

  3. spring框架学习(三)——AOP( 面向切面编程)

    AOP 即 Aspect Oriented Program 面向切面编程 首先,在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能. 所谓的核心业务,比如登陆,增加数据,删除数据都叫核心业务 ...

  4. Spring框架学习05——AOP相关术语详解

    1.Spring AOP 的基本概述 AOP(Aspect Oriented Programing)面向切面编程,AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码(性能监视.事务管理.安全检查 ...

  5. Spring基础学习(四)—AOP

    一.AOP基础 1.基本需求      需求: 日志功能,在程序执行期间记录发生的活动. ArithmeticCalculate.java public interface ArithmeticCal ...

  6. Spring框架学习06——AOP底层实现原理

    在Java中有多种动态代理技术,如JDK.CGLIB.Javassist.ASM,其中最常用的动态代理技术是JDK和CGLIB. 1.JDK的动态代理 JDK动态代理是java.lang.reflec ...

  7. spring框架学习(六)AOP

    AOP(Aspect-OrientedProgramming)面向方面编程,与OOP完全不同,使用AOP编程系统被分为方面或关注点,而不是OOP中的对象. AOP的引入 在OOP面向对象的使用中,无可 ...

  8. Spring框架学习总结(上)

    目录 1.Spring的概述 2.Spring的入门(IOC) 3.Spring的工厂类 4.Spring的配置 5.Spring的属性注入 6.Spring的分模块开发的配置 @ 1.Spring的 ...

  9. Spring框架学习笔记(1)

    Spring 框架学习笔记(1) 一.简介 Rod Johnson(spring之父) Spring是分层的Java SE/EE应用 full-stack(服务端的全栈)轻量级(跟EJB比)开源框架, ...

  10. Spring框架学习1

    AnonymouL 兴之所至,心之所安;尽其在我,顺其自然 新随笔 管理   Spring框架学习(一)   阅读目录 一. spring概述 核心容器: Spring 上下文: Spring AOP ...

随机推荐

  1. css修改select下拉列表的默认样式

    select的一些默认样式我们很难修改,比如图标的替换.接下来就说说如何修改这些默认样式: html代码: <div> <select name=""> & ...

  2. Jq_$.getJSON( )

    jQuery中的$.getJSON( )方法函数主要用来从服务器加载json编码的数据,它使用的是GET HTTP请求.使用方法如下: $.getJSON( url [, data ] [, succ ...

  3. MFC学习笔记(一): 不用MFC向导如何新建一个MFC程序

    使用Visual Studio新建一个空项目,项目命名为HelloMFC,完成后,打开项目属性页面,将配置属性选项卡中的常规项打开,将其中的MFC的使用属性栏改为:在静态库中使用MFC或者在共享DLL ...

  4. selenium+ python自动化--断言assertpy

    前言: 在对登录验证时,不知道为何原因用unittest的断言不成功,就在网上发现这个assertpy,因此做个笔记 准备: pip install assertypy 例子: from assert ...

  5. Unity实现简单的AR

    ,本篇是我在博客园上第一次写随笔,有什么不对或者问题可以在评论区留言告诉我哈! 关于AR(增强现实技术(Augmented Reality))简单的概念,在这里就不说了,有兴趣的同学可以上网详细了解, ...

  6. muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制

    目录 muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制 eventfd的使用 eventfd系统函数 使用示例 EventLoop对eventfd的封装 工作时序 runInLoo ...

  7. Individual Project Records

    At the midnight of September 20, I finished my individual projcet -- a word frequency program. You c ...

  8. 20135316王剑桥Linux内核学习笔记

    王剑桥Linux内核学习笔记 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 计算机是如何工作的 个人理 ...

  9. 框架-Spring

    项目中都用到了Spring.Mybatis.SpringMVC框架,首先来谈一谈Spring框架,Spring框架以IOC.AOP作为主要思想. IOC----控制反转 IOC的全称为Inversio ...

  10. C++:多态浅析

    1.多态 在C++中由两种多态性: • 编译时的多态性:通过函数的重载和运算符的重载来实现的 • 运行时的多态性:通过类继承关系和虚函数来实现的 特别注意: a.运行时的多态性是指程序执行前,无法根据 ...