zoukankan      html  css  js  c++  java
  • 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>
    

      

      

  • 相关阅读:
    程序的局部性原理2
    程序的局部性原理
    ROM
    学习Spring Security OAuth认证(一)-授权码模式
    mybatis*中DefaultVFS的logger乱码问题
    maven生命周期绑定要点
    spring security antMatchers相关内容
    JSTL
    什么是CSS hack?
    Java中获得当前静态类的类名
  • 原文地址:https://www.cnblogs.com/nn369/p/8058208.html
Copyright © 2011-2022 走看看