AOP(Aspect Oriented Programming),即面向切面编程

AOP技术,它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。例如:日志,事务,

使用"横切"技术,AOP把软件系统分为两个部分:核心关注点横切关注点。业务处理的主要流程是核心关注点,与之关系不大的部分是横切关注点。横切关注点的一个特点是,他们经常发生在核心关注点的多处,而各处基本相似,比如权限认证、日志、事物。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点分离开来。

AOP核心概念

1、横切关注点

对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点

2、切面(aspect)

类是对物体特征的抽象,切面就是对横切关注点的抽象

3、连接点(joinpoint)

被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器

4、切入点(pointcut)

对连接点进行拦截的定义

5、通知(advice)

所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类

6、目标对象

代理的目标对象

7、织入(weave)

将切面应用到目标对象并导致代理对象创建的过程

8、引入(introduction)

在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段

Spring中AOP代理由Spring的IOC容器负责生成、管理,其依赖关系也由IOC容器负责管理。因此,AOP代理可以直接使用容器中的其它bean实例作为目标,这种关系可由IOC容器的依赖注入提供。

一,静态代理

package com.dkt.proxy;

import java.util.List;

import com.dkt.dao.IGoods;
import com.dkt.dao.impl.Goodsdao; public class StatisProxy implements IGoods{ private Goodsdao goods; public StatisProxy(Goodsdao goods) {
super();
this.goods = goods;
} /*
* 静态代理,直接实现和impl类实现相同的接口,
* 实现方法,代码冗余
*/
public boolean deleteUser(int id) {
System.out.println("kaishi......");
goods.deleteUser(id);
System.out.println("jiesu.......");
return false;
} public List queryUser() {
// TODO Auto-generated method stub
return null;
}
}

二,jdk实现动态代理

package com.dkt.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; public class InvocationProxy implements InvocationHandler{ private Object obj;
public InvocationProxy(Object obj) {
super();
this.obj = obj;
}
/*
* 动态代理,实现任意的类和方法调用都会执行
*/
public static Object getInvocationProxy(Object realobj){
Class<?> classType = realobj.getClass();
return Proxy.newProxyInstance(classType.getClassLoader(),
classType.getInterfaces(), new InvocationProxy(realobj));
} // invoke 自动调用方法
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("begin................");
Object result = method.invoke(obj, args);
System.out.println("end..........................");
return result;
} }

  测试类

package com.dkt.test;

import com.dkt.dao.IGoods;
import com.dkt.dao.IUser;
import com.dkt.dao.impl.Goodsdao;
import com.dkt.dao.impl.Userimpl;
import com.dkt.proxy.InvocationProxy;
import com.dkt.proxy.StatisProxy; public class TestProxy { public static void main(String[] args) { IUser user= (IUser)InvocationProxy.getInvocationProxy(new Userimpl());
user.saveUser();
user.queryList(); IGoods goods = (IGoods)InvocationProxy.getInvocationProxy(new Goodsdao());
goods.queryUser();
goods.deleteUser(2); // 静态代理测试
/* StatisProxy proxy = new StatisProxy(new Goodsdao());
proxy.deleteUser(3);*/
}
}

三,spring 配置动态代理

1,代理工具类

package com.dkt.util;

import org.aspectj.lang.ProceedingJoinPoint;

public class ProxyUtil {

	public void before(){
System.out.println("执行前-------->");
} public void after(){
System.out.println("执行后------>");
}
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("环绕开始-------");
Object proceed = joinPoint.proceed();
System.out.println("环绕结束--------------");
return proceed;
} public void afterThrow(){
System.out.println("异常啦。。。。");
}
}

2,applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- spring 管理hibernate -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean> <bean id="other" class="com.dkt.util.ProxyUtil"/>
<!-- 配置AOP -->
<aop:config>
<aop:pointcut expression="execution(* com.dkt.dao.IUser.*(..))" id="po"/>
<aop:aspect id="aopOther" ref="other">
<aop:before method="before" pointcut-ref="po"/>
<aop:after method="after" pointcut-ref="po"/>
<aop:around method="around" pointcut-ref="po"/>
<aop:after-throwing method="afterThrow" pointcut-ref="po"/>
</aop:aspect>
</aop:config>
<bean name="userimpl" class="com.dkt.dao.impl.UserImpl" /> <bean id="trans" class="com.dkt.transaction.SessionManager"/>
<aop:config>
<aop:pointcut expression="execution(* com.dkt.dao.*.*(..))" id="pc"/>
<aop:aspect id="aoptrans" ref="trans">
<aop:before method="beginSession" pointcut-ref="pc"/>
<aop:after method="commitSession" pointcut-ref="pc"/>
<aop:after-throwing method="rollbackSession" pointcut-ref="pc"/>
</aop:aspect>
</aop:config> <bean id="dept" class="com.dkt.dao.impl.DeptableDao"/> </beans>

  3,UserImpl 类

package com.dkt.dao.impl;

import java.util.List;

import com.dkt.dao.IUser;
import com.dkt.model.UserInfo; public class UserImpl implements IUser{ public void delete(int i) {
System.out.println("删除----"+i);
} public void query() {
System.out.println("查询--------------");
// int i=10/0;
} public void saveUser(UserInfo ui) {
System.out.println("保存-----------");
} }

  4,测试类

package com.dkt.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dkt.dao.IUser; public class TestAop { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
IUser user = (IUser)context.getBean("userimpl", IUser.class);
// user.delete(3);
user.query();
// user.saveUser(new UserInfo()); }
}

  5,使用动态代理 配置 事务

SessionManager 事务处理工具类
package com.dkt.transaction;

import org.hibernate.classic.Session;

import com.dkt.dao.impl.BaseDao;

public class SessionManager {

	/*
* 事务切面处理
*/
public void beginSession(){
Session session = BaseDao.factory.getCurrentSession();
session.getTransaction().begin();
System.out.println("事务开启了。。。 ");
}
public void commitSession(){
Session session = BaseDao.factory.getCurrentSession();
session.getTransaction().commit();
System.out.println("事务提交。。。 ");
}
public void rollbackSession(){
Session session = BaseDao.factory.getCurrentSession();
session.getTransaction().rollback();
System.out.println("事务异常回滚了。。。 ");
} }

  BaseDao

package com.dkt.dao.impl;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session; public class BaseDao { public static SessionFactory factory = null;
static{
Configuration configure = new Configuration().configure();
factory = configure.buildSessionFactory();
} public boolean saveOld(Object dep){
Session session = factory.openSession();
Transaction transaction = session.beginTransaction();
try {
session.save(dep);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}finally{
session.close();
}
return false;
}
public boolean saveNew(Object dep){
Session session = factory.getCurrentSession();
session.save(dep);
return true;
} }

  DeptableDao 部门Dao类

package com.dkt.dao.impl;

import com.dkt.dao.IDeptableDao;
import com.dkt.model.Deptable; public class DeptableDao extends BaseDao implements IDeptableDao { public boolean saveNewDeptable(Deptable dep) {
return super.saveNew(dep);
} public boolean saveOldDeptable(Deptable dep) {
return super.saveOld(dep);
} }

  hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/marry?userUnicode=true&characterEncoding=utf-8
</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">
Mysqlmarrybase
</property> <property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 配置factory.getCurrentSeesion()方式得到session -->
<property name="current_session_context_class">thread</property> <mapping resource="com/dkt/model/Deptable.hbm.xml" />
</session-factory> </hibernate-configuration>

Deptable.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.dkt.model.Deptable" table="deptable" catalog="marry">
<id name="depid" type="java.lang.Integer">
<column name="depid" />
<generator class="identity" />
</id>
<property name="depname" type="java.lang.String">
<column name="depname" length="20" not-null="true" />
</property> </class>
</hibernate-mapping>

测试事务

package com.dkt.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dkt.dao.IDeptableDao;
import com.dkt.model.Deptable; public class TestTransacion { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
IDeptableDao deptableDao = (IDeptableDao)context.getBean("dept");
Deptable deptable = new Deptable("公安部");
// deptableDao.saveOldDeptable(deptable);
deptableDao.saveNewDeptable(deptable);
}
}

拓展spring 系统自带的事务管理,传播特性和隔离级别

<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
"> <!-- 管理hibernate, 创建sessionFactory对象 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 引入系统的事务管理管理通知 name不可变-->
<bean id="trans" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务的传播特性,隔离级别 -->
<tx:advice id="tdAdvice" transaction-manager="trans">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
<tx:method name="delete*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
<tx:method name="query*" propagation="SUPPORTS" isolation="DEFAULT"/>
<tx:method name="update*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
<tx:method name="page*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP切面 -->
<aop:config>
<aop:pointcut expression="execution(* com.dkt.dao.*.*(..))" id="pc"/>
<aop:advisor advice-ref="tdAdvice" pointcut-ref="pc"/>
</aop:config> <!-- 配置dao实现类,类中由接口接受,name不可变 -->
<bean id="userinfodao" class="com.dkt.dao.impl.UserinfoDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> </beans>

  

  

spring AOP 动态代理和静态代理以及事务的更多相关文章

  1. spring aop 动态代理批量调用方法实例

    今天项目经理发下任务,需要测试 20 个接口,看看推送和接收数据是否正常.因为对接传输的数据是 xml 格式的字符串,所以我拿现成的数据,先生成推送过去的数据并存储到文本,以便验证数据是否正确,这时候 ...

  2. Atitit 代理CGLIB 动态代理 AspectJ静态代理区别

    Atitit 代理CGLIB 动态代理 AspectJ静态代理区别 1.1. AOP 代理主要分为静态代理和动态代理两大类,静态代理以 AspectJ 为代表:而动态代理则以 spring AOP 为 ...

  3. 【Java】代处理?代理模式 - 静态代理,动态代理

    >不用代理 有时候,我希望在一些方法前后都打印一些日志,于是有了如下代码. 这是一个处理float类型加法的方法,我想在调用它前打印一下参数,调用后打印下计算结果.(至于为什么不直接用+号运算, ...

  4. SpringAOP用到了什么代理,以及动态代理与静态代理的区别

    spring aop (面向切面)常用于数据库事务中,使用了2种代理. jdk动态代理:对实现了接口的类生成代理对象.要使用jdk动态代理,要求类必须要实现接口. cglib代理:对类生成代理对象. ...

  5. Java代理模式/静态代理/动态代理

    代理模式:即Proxy Pattern,常用的设计模式之一.代理模式的主要作用是为其他对象提供一种代理以控制对这个对象的访问. 代理概念 :为某个对象提供一个代理,以控制对这个对象的访问. 代理类和委 ...

  6. Spring AOP 源码分析 - 创建代理对象

    1.简介 在上一篇文章中,我分析了 Spring 是如何为目标 bean 筛选合适的通知器的.现在通知器选好了,接下来就要通过代理的方式将通知器(Advisor)所持有的通知(Advice)织入到 b ...

  7. java 基础 --- 动态代理和静态代理

    问题  : 代理的应用场景是什么 动态代理的底层原理是什么,为什么只能继承接口 概述 代理模式是设计模式的一种,简单地说就是调用代理类的方法实际就是调用真实类的方法.这种模式在AOP (切面编程)中非 ...

  8. Java代理(静态代理、JDK动态代理、CGLIB动态代理)

    Java中代理有静态代理和动态代理.静态代理的代理关系在编译时就确定了,而动态代理的代理关系是在运行期确定的.静态代理实现简单,适合于代理类较少且确定的情况,而动态代理则给我们提供了更大的灵活性. J ...

  9. Spring AOP系列(一)— 代理模式

    Spring AOP系列(一)- 代理模式 AOP(Aspect Oriented Programming)并没有创造或使用新的技术,其底层就是基于代理模式实现.因此我们先来学习一下代理模式. 基本概 ...

  10. Java中的代理模式--静态代理和动态代理本质理解

    代理模式定义:为其他对象提供了一种代理以控制对这个对象的访问. 代理模式的三种角色: Subject抽象主题角色:抽象主题类可以是抽象类也可以是接口,是一个最普通的业务类型定义,无特殊要求. Real ...

随机推荐

  1. Python面向对象(类的成员之方法)

    day24 类的成员之方法 - 普通方法,保存在类中,由对象来调用,self > 对象 - 静态方法,保存在类中,由类直接调用 - 类方法,保存在类中,由类直接调用,cls > 当前类 c ...

  2. Android安全防护防护———加密算法

    摘要 这篇文章本来早就应该写了,但是由于项目一直开发新的需求,就拖后了.现在有时间了,必须得写了.现在Android应用程序对安全防范这方面要求越来越高了.特别是金融行业,如果金融app没有没有做好相 ...

  3. nginx代理websocket协议

    以下是代码段.location /wsapp/ {     proxy_pass http://wsbackend;     proxy_http_version 1.1;     proxy_set ...

  4. mysql 练习 和链接 pymysql 练习题

    python操作数据库 1. 查询student表的所有记录 2. 查询student表的第2条到第4条记录 3. 查询所有学生的学号(id).姓名(name)和报读课程(department)的信息 ...

  5. OpenCV2计算机编程手册(二)基于类的图像处理

    1. 在算法设计中使用策略(Strategy)模式 策略设计模式的目标是将算法封装在类中.因此,可以更容易地替换一个现有的算法,或者组合使用多个算法以拥有更复杂的处理逻辑.此外,该模式将算法的复杂度隐 ...

  6. Linux必备命令

      目录                                                              概述 常用系统工作命令 系统状态检测命令 工作目录切换命令 文本文件 ...

  7. 【bzoj2961】共点圆 k-d树

    更新:此题我的代码设置eps=1e-8会WA,现在改为1e-9貌似T了 此题网上的大部分做法是cdq分治+凸包,然而我觉得太烦了,于是自己口胡了一个k-d树做法: 加入一个圆$(x,y)$,直接在k- ...

  8. JSON 字符串转换为JavaScript 对象.JSON.parse()和JSON.stringify()

    使用 JavaScript 内置函数 JSON.parse() 将字符串转换为 JavaScript 对象: var text = '{ "sites" : [' + '{ &qu ...

  9. J03-Java IO流总结三 《 FileInputStream和FileOutputStream 》

    1. FileInputStream    FileInputStream是一个文件输入节点流,它是一个字节流,它的作用是将磁盘文件的内容读取到内存中. FileInputStream的父类是Inpu ...

  10. (转)python中math模块常用的方法整理

    原文:https://www.cnblogs.com/renpingsheng/p/7171950.html#ceil ceil:取大于等于x的最小的整数值,如果x是一个整数,则返回x copysig ...