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. CSS3盒子模型(下)

    绝对定位的盒子水平/垂直居中 普通的盒子是左右margin 改为 auto就可, 但是对于绝对定位就无效了 定位的盒子也可以水平或者垂直居中,有一个算法. 首先left 50% 父盒子的一半大小 然后 ...

  2. javaWeb登录注册页面

    简单的登陆注册页面 1.配置JDBC驱动连接数据库 2. 配置struts2框架 3. 利用1 2完成登录页面, 注意做到不耦合,即servlet Api和控制器完全脱离) 4. 利用1 2 制作注册 ...

  3. 用absolute进行页面的自适应布局

    用position:absolute和top,left,bottom,right进行设置可以进行页面的头部,底部,左边框,内容的自适应布局,可以代替position:fixed; <!DOCTY ...

  4. js创建对象方法

    1.对象字面量 let xys={ name:'xys', age:22, height:177 } console.log(xys.age)  //22   2.使用new操作符和构造函数    1 ...

  5. Swift的Guard语句

    与if语句相同的是,guard也是基于一个表达式的布尔值去判断一段代码是否该被执行.与if语句不同的是,guard只有在条件不满足的时候才会执行这段代码.你可以把guard近似的看做是Assert,但 ...

  6. 剑指offer二十九之最小的K个数

    一.题目 输入n个整数,找出其中最小的K个数.例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,. 二.思路 详解代码. 三.代码 import java.util. ...

  7. Hive Cli相关操作

    landen@Master:~/UntarFile/hive-0.10.0$ bin/hive --database 'stuchoosecourse' -e 'select * from hidde ...

  8. 全网最详细使用Scrapy时遇到0: UserWarning: You do not have a working installation of the service_identity module: 'cannot import name 'opentype''. Please install it from ..的问题解决(图文详解)

    不多说,直接上干货! 但是在运行爬虫程序的时候报错了,如下: D:\Code\PycharmProfessionalCode\study\python_spider\30HoursGetWebCraw ...

  9. javac后期需要重点阅读的类

    (1)Annotate (300行) Enter annotations on symbols. Annotations accumulate in a queue,which is processe ...

  10. sql典例分析

    1. 条件过滤 & Having 表结构 #tab_a #tab_b 表关系 tab_a.id = tab_b.relation_id 表数据 需求 查新把tab_a的ID对应的表tab_b的 ...