spring AOP 动态代理和静态代理以及事务
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 动态代理和静态代理以及事务的更多相关文章
- spring aop 动态代理批量调用方法实例
今天项目经理发下任务,需要测试 20 个接口,看看推送和接收数据是否正常.因为对接传输的数据是 xml 格式的字符串,所以我拿现成的数据,先生成推送过去的数据并存储到文本,以便验证数据是否正确,这时候 ...
- Atitit 代理CGLIB 动态代理 AspectJ静态代理区别
Atitit 代理CGLIB 动态代理 AspectJ静态代理区别 1.1. AOP 代理主要分为静态代理和动态代理两大类,静态代理以 AspectJ 为代表:而动态代理则以 spring AOP 为 ...
- 【Java】代处理?代理模式 - 静态代理,动态代理
>不用代理 有时候,我希望在一些方法前后都打印一些日志,于是有了如下代码. 这是一个处理float类型加法的方法,我想在调用它前打印一下参数,调用后打印下计算结果.(至于为什么不直接用+号运算, ...
- SpringAOP用到了什么代理,以及动态代理与静态代理的区别
spring aop (面向切面)常用于数据库事务中,使用了2种代理. jdk动态代理:对实现了接口的类生成代理对象.要使用jdk动态代理,要求类必须要实现接口. cglib代理:对类生成代理对象. ...
- Java代理模式/静态代理/动态代理
代理模式:即Proxy Pattern,常用的设计模式之一.代理模式的主要作用是为其他对象提供一种代理以控制对这个对象的访问. 代理概念 :为某个对象提供一个代理,以控制对这个对象的访问. 代理类和委 ...
- Spring AOP 源码分析 - 创建代理对象
1.简介 在上一篇文章中,我分析了 Spring 是如何为目标 bean 筛选合适的通知器的.现在通知器选好了,接下来就要通过代理的方式将通知器(Advisor)所持有的通知(Advice)织入到 b ...
- java 基础 --- 动态代理和静态代理
问题 : 代理的应用场景是什么 动态代理的底层原理是什么,为什么只能继承接口 概述 代理模式是设计模式的一种,简单地说就是调用代理类的方法实际就是调用真实类的方法.这种模式在AOP (切面编程)中非 ...
- Java代理(静态代理、JDK动态代理、CGLIB动态代理)
Java中代理有静态代理和动态代理.静态代理的代理关系在编译时就确定了,而动态代理的代理关系是在运行期确定的.静态代理实现简单,适合于代理类较少且确定的情况,而动态代理则给我们提供了更大的灵活性. J ...
- Spring AOP系列(一)— 代理模式
Spring AOP系列(一)- 代理模式 AOP(Aspect Oriented Programming)并没有创造或使用新的技术,其底层就是基于代理模式实现.因此我们先来学习一下代理模式. 基本概 ...
- Java中的代理模式--静态代理和动态代理本质理解
代理模式定义:为其他对象提供了一种代理以控制对这个对象的访问. 代理模式的三种角色: Subject抽象主题角色:抽象主题类可以是抽象类也可以是接口,是一个最普通的业务类型定义,无特殊要求. Real ...
随机推荐
- 什么是Ajax?Ajax的原理是什么?Ajax的核心技术是什么?Ajax的优缺点是什么?
Ajax是一种无需重新加载整个网页,能够更新部分网页的技术.Asynchronous JavaScript and XML的缩写,是JavaScript.XML.CSS.DOM等多个技术的组合. Aj ...
- Zookeeper原理分析之存储结构Snapshot
Zookeeper内存结构 Zookeeper数据在内存中的结构类似于linux的目录结构,DataTree代表这个目录结构, DataNode代表一个节点.DataTree默认初始化三个目录:&qu ...
- redis cluster 添加 删除 重分配 节点
redis cluster配置好,并运行一段时间后,我们想添加节点,或者删除节点,该怎么办呢. 一,redis cluster命令 //集群(cluster) CLUSTER INFO 打印集群的信 ...
- git 忽略某些文件的命令
正常的,我们在提交项目版本的时候,经常会存在一些需要忽略的文件或者文件夹,那这个时候,我们就可以通过git的一些操作命令来实现! vim .gitignore 通过上面一句话进入编辑忽略文件/文件夹的 ...
- python3异常处理 try
一. 简介 在编程过程中为了增加友好性,在程序出现Bug时一般不会直接将错误信息展示给用户,而是提供一个友好的输出提示. 二. 使用 1.异常基础 常用结构: try: pass except Exc ...
- linux下mysql主从复制搭建
目标:搭建两台MySQL服务器,一台作为主服务器,一台作为从服务器,实现主从复制 环境: 主数据库: 192.168.1.1 从数据库: 192.168.1.2 mysql安装可参考:https:// ...
- Java之集合(十三)WeakHashMap
转载请注明源出处:http://www.cnblogs.com/lighten/p/7423818.html 1.前言 本章介绍一下WeakHashMap,这个类也很重要.要想明白此类的作用,先要明白 ...
- Python的不定长参数研究
通过观察程序和运行结果我们发现,传参时将1传给了a,将2传给了b,将3,4,5传给了*args,将m=6,n=7,p=8传给了**kwargs.为什么是这样传参呢?*args和**kwargs又是什 ...
- 浅谈Android Studio中项目结构中project模式的各个文件和文件夹
致敬郭霖,这些知识是从第一行代码第二版中直接码下来的,谢谢他,注意每个条目前是否有. 1..gradle和.idea 这两个目录下放置的都是Android Studio自动生成的一些文件,我们无需关心 ...
- WordPress主题制作导航的N种方法
在WordPress主 题制作中,导航菜单的制作算是一个重点,已经写好导航菜单的HTML代码,放在WordPress主题中如何动态调用呢?本文将给你介绍几种编写PHP代 码动态实现导航的方法,本文也将 ...