`
GavinZheng
  • 浏览: 16024 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

Spring AOP

阅读更多
AOP
Spring AOP:面象切面编程,即织入增强,以子类的形式去扩展及重写。核心通过代理类去实现,例如服务层中的一个Server类中有几个方法添加用户,删除用户,更新用户,查询用户信息,分别调用Dao层中添加用户,删除用户,更新用户,查询用户信息的方法,但在调用前需要做性能测试,日志记录,事务启动等动作。结束后需要做性能测试结果报告,日志结束,事务的提交等操作,发生异常时需要使用异常处理逻辑,此时将性能测试,日志记录,事务,及异常处理逻辑抽取出来,交由代理,还服务层一块纯净的空间,在调用Server类中的方法时,先由代理将事务等方法织入并执行。

实现核心:JDK动态代理和CGLib代理组成
两者的区别:
一、 JDK动态代理代理的目标类需要实现接口,而CGLib则不需要类去实现接口。
二、 JDK使用的是JAVA反射机制生成,而CGLib则是生成了一个新的子类。

织入的方式有三种:
a. 编译期织入,要求使用特殊的JAVA编译器。
b. 类装载期织入,要求使用特殊的类装载器。
c. 运行期织入,在运行期为目标类添加增强生成子类的方式。
Spring采用动态代理织入,而AspectJ采用的是编译期织入,类装载期织入。

切点五个位置:
a. @Before() 执行目标类方法前
b. @AfterReturning() 执行目标类方法后
c. @After() 无论如何都会执行
d. @AfterThrowing() 异常产生时执行
e. @Around() 有固定的格式,在方法执行前后,可取代@Before(),@AfterReturning()。其固定格式为:
@Around("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
System.out.println("进入方法");
Object retVal = pjp.proceed();
System.out.println("退出方法");
// stop stopwatch
return retVal;
}
注意:@Before()可接受目标类方法的传递参数。@AfterReturning()接受目标类方法返回值,做为其参数传递。@AfterThrowing()可接收发生的异常

Spring AOP实现具体步骤:
1. 编写Service层的接口。
2. 编写Service层的接口实现类。
3. 编写切面类及增强的方法。
4. 在配置文件中配置。
5. 调试。

package org.service.person;

public interface PeronService {
	public void savePserson(String name);
	public void updatePerson(String name,Integer personID);
	public String getPersonName(Integer personID);
}


package org.service.person.imp;

import org.service.person.PeronService;

public class PersonServiceImp implements PeronService {
	private String name = null;

	public PersonServiceImp() {
	}

	public PersonServiceImp(String name) {
		this.name = name;
	}

	public void savePserson(String name) {
		System.out.println("savePserson方法");
	}

	public void updatePerson(String name, Integer personID) {
		throw new RuntimeException("我是例外");
		// System.out.println("updatePerson方法");
	}

	public String getPersonName(Integer personID) {
		System.out.println("getPersonName方法");
		return "xxxx";
	}

	public String getName() {
		return this.name;
	}

}


package org.service.person.intercep;

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 InterceptPersonservice {
	@Pointcut("execution(* org.service.person..*(..))")
	public void anyMethod() {
	}

	@Before("anyMethod() && args(name)")
	public void doBefore(String name) {
		System.out.println("我是前置增强:" + name);
	}

	@AfterReturning(pointcut = "anyMethod()", returning = "result")
	public void doAfterReturning(String result) {
		System.out.println("我是后置增强:" + result);
	}

	@After("anyMethod()")
	public void doAfter() {
		System.out.println("我是最终增强");
	}

	@AfterThrowing(pointcut = "anyMethod()", throwing = "e")
	public void doAfterThrowing(Exception e) {
		System.out.println("我是异常增强:" + e);
	}

	@Around("anyMethod()")
	public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
		// start stopwatch
		System.out.println("进入方法");
		Object retVal = pjp.proceed();
		System.out.println("退出方法");
		// stop stopwatch
		return retVal;
	}

}


<?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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
				http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

	<!-- <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" 
		/> -->

	<aop:aspectj-autoproxy>
		<!-- Explicit testing the whitespace body variant here -->
	</aop:aspectj-autoproxy>

	<bean id="personServiceImp" class="org.service.person.imp.PersonServiceImp" />
	<bean id="interceptPersonservice" class="org.service.person.intercep.InterceptPersonservice" />
</beans>


package org.junit.test;

import org.junit.Test;
import org.proxy.CGLibFactory;
import org.proxy.ProxyFactory;
import org.service.person.PeronService;
import org.service.person.imp.PersonServiceImp;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringAOPTest {

	@Test
	public void springAOPTest() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"org/service/person/springAop.xml");
		PeronService peronService = (PeronService) applicationContext
				.getBean("personServiceImp");
		peronService.savePserson("xx");
		System.out.println("---------------------");
		peronService.getPersonName(2);
		System.out.println("---------------------");
		peronService.updatePerson("xx", 2);
	}
}


JDK编写代理类
package org.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.service.person.imp.PersonServiceImp;

public class ProxyFactory implements InvocationHandler{
	private Object object;
	public Object createProxyInstace(Object object){
		this.object = object;
		return Proxy.newProxyInstance(this.object.getClass().getClassLoader(), this.object.getClass().getInterfaces(), this);
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		PersonServiceImp personServiceImp = (PersonServiceImp) this.object;
		Object result = null;
//		System.out.println(personServiceImp.getName());
		if (personServiceImp.getName()!=null) {
			result = method.invoke(this.object, args);
		}
		return result;
	}
}


CGLib实现
package org.proxy;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.service.person.imp.PersonServiceImp;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CGLibFactory implements MethodInterceptor{
	private Object object;
	public Object createCGLibInstace(Object object){
		this.object = object;
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(this.object.getClass());
		enhancer.setCallback(this);
		return enhancer.create();
	}
	public Object intercept(Object arg0, Method arg1, Object[] arg2,
			MethodProxy arg3) throws Throwable {
		PersonServiceImp personServiceImp = (PersonServiceImp) this.object;
		Object result = null;
//		System.out.println(personServiceImp.getName());
		if (personServiceImp.getName()!=null) {
			result = arg3.invoke(this.object, arg2);
		}
		return result;
	}
}


测试:JDK动态代理和CGLib代理
package org.junit.test;

import org.junit.Test;
import org.proxy.CGLibFactory;
import org.proxy.ProxyFactory;
import org.service.person.PeronService;
import org.service.person.imp.PersonServiceImp;


public class ProxyTest {

	@Test
	public void personProxyTest(){
		ProxyFactory proxyFactory = new ProxyFactory();
		PersonServiceImp personServiceImp = new PersonServiceImp();
		PersonServiceImp personServiceImp2 = new PersonServiceImp("aaa");
		
		PeronService peronService = (PeronService)proxyFactory.createProxyInstace(personServiceImp);
		peronService.savePserson("xxx");
		System.out.println("----------");
		PeronService peronService2 = (PeronService)proxyFactory.createProxyInstace(personServiceImp2);
		peronService2.savePserson("xxx");
	}
	@Test
	public void cgLibTest(){
		CGLibFactory cglibFactory = new CGLibFactory();
		PersonServiceImp personServiceImp = new PersonServiceImp();
		PersonServiceImp personServiceImp2 = new PersonServiceImp("aaa");
		
		PersonServiceImp peronService = (PersonServiceImp)cglibFactory.createCGLibInstace(personServiceImp);
		peronService.savePserson("xxx");
		System.out.println("----------");
		PersonServiceImp peronService2 = (PersonServiceImp)cglibFactory.createCGLibInstace(personServiceImp2);
		peronService2.savePserson("xxx");
	}
}

分享到:
评论

相关推荐

    spring aop jar 包

    Spring AOP(Aspect Oriented Programming,面向切面编程)是Spring框架的重要组成部分,它提供了一种在不修改源代码的情况下,对程序进行功能增强的技术。这个"spring aop jar 包"包含了实现这一功能所需的类和接口,...

    Spring AOP 16道面试题及答案.docx

    Spring AOP,全称为Aspect Oriented Programming,是面向切面编程的一种编程范式,它是对传统的面向对象编程(OOP)的一种补充。在OOP中,核心是对象,而在AOP中,核心则是切面。切面是关注点的模块化,即程序中的...

    简单spring aop 例子

    Spring AOP(面向切面编程)是Spring框架的重要组成部分,它提供了一种模块化和声明式的方式来处理系统中的交叉关注点问题,如日志、事务管理、安全性等。本示例将简要介绍如何在Spring应用中实现AOP,通过实际的...

    spring aop 自定义注解保存操作日志到mysql数据库 源码

    3、对spring aop认识模糊的,不清楚如何实现Java 自定义注解的 4、想看spring aop 注解实现记录系统日志并入库等 二、能学到什么 1、收获可用源码 2、能够清楚的知道如何用spring aop实现自定义注解以及注解的逻辑...

    死磕Spring之AOP篇 - Spring AOP两种代理对象的拦截处理(csdn)————程序.pdf

    Spring AOP 是一种面向切面编程的技术,它允许我们在不修改源代码的情况下,对应用程序的特定部分(如方法调用)进行增强。在 Spring 中,AOP 的实现主要依赖于代理模式,有两种代理方式:JDK 动态代理和 CGLIB 动态...

    Spring AOP完整例子

    Spring AOP(面向切面编程)是Spring框架的核心特性之一,它允许开发者在不修改源代码的情况下,通过插入切面来增强或改变程序的行为。在本教程中,我们将深入探讨Spring AOP的不同使用方法,包括定义切点、通知类型...

    Spring Aop四个依赖的Jar包

    Spring AOP,全称Aspect-Oriented Programming(面向切面编程),是Spring框架的一个重要模块,它通过提供声明式的方式来实现面向切面编程,从而简化了应用程序的开发和维护。在Spring AOP中,我们无需深入到每个...

    spring aop依赖jar包

    现在,我们回到主题——"springaop依赖的jar包"。在Spring 2.5.6版本中,使用Spring AOP通常需要以下核心jar包: - `spring-aop.jar`:这是Spring AOP的核心库,包含了AOP相关的类和接口。 - `spring-beans.jar`:...

    spring AOP 引入jar包,spring IOC 引入Jar包

    Spring AOP 和 Spring IOC 是 Spring 框架的两个核心组件,它们对于任何基于 Java 的企业级应用开发都至关重要。Spring AOP(面向切面编程)允许开发者在不修改源代码的情况下,通过“切面”来插入新的行为或增强已...

    反射实现 AOP 动态代理模式(Spring AOP 的实现原理)

    面向切面编程(AOP)是一种编程范式,旨在将横切关注点(如日志、安全等)与业务逻辑分离,从而提高模块化。...利用Java反射机制和Spring AOP框架,开发者可以方便地实现AOP,从而提升代码的模块化和可维护性。

    Spring AOP实现机制

    **Spring AOP 实现机制详解** Spring AOP(面向切面编程)是Spring框架的核心特性之一,它允许程序员在不修改源代码的情况下,通过“切面”来插入额外的业务逻辑,如日志、事务管理等。AOP的引入极大地提高了代码的...

    springAOP配置动态代理实现

    Spring AOP(面向切面编程)是Spring框架的重要组成部分,它允许程序员在不修改源代码的情况下,通过在运行时插入额外的行为(如日志记录、性能监控等)来增强对象的功能。动态代理则是Spring AOP实现的核心技术之一...

    Spring AOP面向方面编程原理:AOP概念

    ### Spring AOP面向方面编程原理:AOP概念详解 #### 一、引言 随着软件系统的日益复杂,传统的面向对象编程(OOP)逐渐暴露出难以应对某些横切关注点(cross-cutting concerns)的问题。为了解决这一挑战,面向方面编程...

    小马哥讲 Spring AOP 编程思想 - API 线索图.pdf

    在讨论Spring AOP(面向切面编程)时,首先需要理解几个核心概念。Spring AOP 是Spring框架提供的一个功能模块,它允许开发者将横切关注点(cross-cutting concerns)从业务逻辑中解耦出来,通过在方法调用前后进行...

    spring aop切面拦截指定类和方法实现流程日志跟踪

    ### Spring AOP 实现流程日志跟踪 #### 一、背景与目的 在现代软件开发过程中,为了确保系统的稳定性和可维护性,通常会引入非功能性的需求来增强应用程序的功能,比如日志记录、安全控制等。这些需求往往不是业务...

    spring aop 五个依赖jar

    Spring AOP(面向切面编程)是Spring框架的重要组成部分,它提供了一种模块化和声明式的方式来处理系统中的交叉关注点,如日志、事务管理等。在Java应用中,AOP通过代理模式实现了切面编程,使得我们可以将业务逻辑...

    Spring AOP 入门作者:廖雪峰

    ### Spring AOP 入门详解 #### 一、Spring AOP 概述 Spring AOP(Aspect Oriented Programming,面向切面编程)是Spring框架的一个关键特性,它为开发者提供了在运行时动态添加代码(即横切关注点或切面)到已有...

    Spring源码最难问题:当Spring AOP遇上循环依赖.docx

    Spring源码最难问题:当Spring AOP遇上循环依赖 Spring源码中最难的问题之一是循环依赖问题,当Spring AOP遇上循环依赖时,该如何解决? Spring通过三级缓存机制解决循环依赖的问题。 在Spring中,bean的实例化...

    spring AOP依赖三个jar包

    Spring AOP,即Spring的面向切面编程模块,是Spring框架的重要组成部分,它允许开发者在不修改源代码的情况下,对程序进行横切关注点的处理,如日志、事务管理等。实现这一功能,主要依赖于三个核心的jar包:aop...

    spring aop的demo

    在`springAop1`这个压缩包中,可能包含了一个简单的应用示例,展示了如何定义一个切面类,以及如何在该类中定义通知方法。例如,我们可能会看到一个名为`LoggingAspect`的类,其中包含了`@Before`注解的方法,用于在...

Global site tag (gtag.js) - Google Analytics