`
jamesby
  • 浏览: 383956 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Spring AOP Sample Code

阅读更多
Before Advice

package test3;
public class MessageWriter {
	public void writeMessage()	{
		System.out.print("World");
	}
}

package test3;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
public class SimpleBeforeAdvice implements MethodBeforeAdvice{
	public void before(Method method,Object[] args,Object target) throws Throwable{
		System.out.println("Before method:"+method.getName());
	}
	public static void main(String[] args){
		MessageWriter target = new MessageWriter();
		ProxyFactory pf = new ProxyFactory();
		pf.addAdvice(new SimpleBeforeAdvice());
		pf.setTarget(target);
		MessageWriter proxy = (MessageWriter)pf.getProxy();
		proxy.writeMessage();
	}
}


AfterReturningAdvice

package test3;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.framework.ProxyFactory;
public class SimpleAfterReturningAdvice implements AfterReturningAdvice{
	public void afterReturning(Object returnValue,Method method,Object[] args,Object target){
		System.out.println("");
		System.out.println("After method:"+method.getName());
	}
public static void main(String[] args) {
		MessageWriter target = new MessageWriter();
		ProxyFactory pf = new ProxyFactory();
		pf.addAdvice(new SimpleAfterReturningAdvice());
		pf.setTarget(target);
		MessageWriter proxy = (MessageWriter)pf.getProxy();
		proxy.writeMessage();
	}
}


Around Advice

package test3;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MessageDecorator implements MethodInterceptor{
	public Object invoke(MethodInvocation invocation) throws Throwable{
		System.out.print("Hello");
		Object retVal = invocation.proceed();
		System.out.println("!");
		return retVal;
	}	
}

package test3;
import org.springframework.aop.framework.ProxyFactory;
public class HelloWorldAOPExample {
	public static void main(String[] args) {
		MessageWriter target=new MessageWriter();
		ProxyFactory pf = new ProxyFactory();
		pf.addAdvice(new MessageDecorator());
		pf.setTarget(target);
		MessageWriter proxy = (MessageWriter)pf.getProxy();
		target.writeMessage();
		System.out.print(" ");
		proxy.writeMessage();
	}
}


ThrowsAdvice

package test3;
public class ErrorBean {
	public void errorProneMethod() throws  Exception{
		throw new  Exception("Foo");
	}
	public void otherErrorProneMethod() throws IllegalArgumentException{
		throw new IllegalArgumentException("Bar");
	}
}

package test3
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;

public class SimpleThrowsAdvice implements ThrowsAdvice{
	public static void main(String[] args) throws Exception {
		ErrorBean errorBean = new ErrorBean();
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(errorBean);
		pf.addAdvice(new SimpleThrowsAdvice());
		ErrorBean proxy = (ErrorBean)pf.getProxy();
		try
		{
			proxy.errorProneMethod();
		}catch(Exception ignored)
		{
			//ignored.printStackTrace();
		}
		try
		{
			proxy.otherErrorProneMethod();
		}catch(Exception ignored)
		{
			//ignored.printStackTrace();
		}		
	}
	public void afterThrowing(Exception ex) throws Throwable{
		System.out.println("***");
		System.out.println("Generic Exception Capture");
		System.out.println("Caught: "+ex.getClass().getName());
		System.out.println("***\n");
	}
	public void afterThrowing(Method method,Object[] args,Object target,IllegalArgumentException ex) throws Throwable{
		System.out.println("***");
		System.out.println("IllegalArgumentException Capture");
		System.out.println("Caught: "+ex.getClass().getName());
		System.out.println("***\n");		
	}
}


StaticPointcut

package test3;
public class BeanOne {
	public void foo() {
		System.out.println("foo");
	}
	public void bar() {
		System.out.println("bar");
	}
}

package test3;
public class BeanTwo {
	public void foo() {
		System.out.println("foo");
	}
	public void bar() {
		System.out.println("bar");
	}
}

package test3;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class SimpleAdvice implements MethodInterceptor{
	public Object invoke(MethodInvocation invocation) throws Throwable
	{
		System.out.println(">> Invoking "+invocation.getMethod().getName());
		Object retVal = invocation.proceed();
		System.out.println(">> Done");
		return retVal;
	}
}

package test3;

import java.lang.reflect.Method;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
public class SimpleStaticPointcut extends StaticMethodMatcherPointcut {
	public boolean matches(Method method, Class cls) {
		return ("foo".equals(method.getName()));
	}
	public ClassFilter getClassFilter() {
		return new ClassFilter() {
			public boolean matches(Class cls) {
				return (cls == BeanOne.class);
			}
		};
	}
}

package test3;
import org.aopalliance.aop.Advice;
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

public class StaticPointcutExample {
	public static void main(String[] args) {
		BeanOne one = new BeanOne();
		BeanTwo two = new BeanTwo();
		
		BeanOne proxyOne;
		BeanTwo proxyTwo;
		
		Pointcut pc = new SimpleStaticPointcut();
		Advice advise = new SimpleAdvice();
		Advisor advisor = new DefaultPointcutAdvisor(pc,advise);
		
		ProxyFactory pf = new ProxyFactory();
		pf.addAdvisor(advisor);
		pf.setTarget(one);
		proxyOne = (BeanOne)pf.getProxy();
		
		pf = new ProxyFactory();
		pf.addAdvisor(advisor);
		pf.setTarget(two);
		proxyTwo = (BeanTwo)pf.getProxy();
		
		proxyOne.foo();
		proxyTwo.foo();
	
		proxyOne.bar();
		proxyTwo.bar();
	}
}


Dynamic pointcut

package test3;
public class SampleBean {
	public void foo(int x){
		System.out.println("Invoked foo() with: "+x);
	}
	public void bar(){
		System.out.println("Invoked bar()");
	}
}

package test3;

import java.lang.reflect.Method;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.DynamicMethodMatcherPointcut;
public class SimpleDynamicPointcut extends DynamicMethodMatcherPointcut{
	public boolean matches(Method method, Class cls) {
		System.out.println("Static check for " + method.getName());
		return ("foo".equals(method.getName()));
	}
	public boolean matches(Method method, Class cls, Object[] args) {
		System.out.println("Dynamic check for " + method.getName());
		int x = ((Integer) args[0]).intValue();
		return (x != 100);
	}
	public ClassFilter getClassFilter() {
		return new ClassFilter() {
			public boolean matches(Class cls) {
				return (cls == SampleBean.class);
			}
		};
	}
}

package test3;

import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
public class DynamicPointcutExample {
	public static void main(String[] args) {
		SampleBean target = new SampleBean();
		Advisor advisor = new DefaultPointcutAdvisor(new SimpleDynamicPointcut(),new SimpleAdvice());
		
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(target);
		pf.addAdvisor(advisor);
		SampleBean proxy = (SampleBean)pf.getProxy();
		
		proxy.foo(1);
		proxy.foo(10);
		proxy.foo(100);
		
		proxy.bar();
		proxy.bar();
		proxy.bar();
	}
}


NamePointcut

package test3;
public class NameBean {
	public void foo() {
		System.out.println("foo");
	}
	public void foo(int x) {
		System.out.println("foo " + x);
	}
	public void bar() {
		System.out.println("bar");
	}
	public void yup() {
		System.out.println("yup");
	}
}

package test3;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class SimpleAdvice implements MethodInterceptor{
	public Object invoke(MethodInvocation invocation) throws Throwable
	{
		System.out.println(">> Invoking "+invocation.getMethod().getName());
		Object retVal = invocation.proceed();
		System.out.println(">> Done");
		return retVal;
	}
}

package test3;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.NameMatchMethodPointcut;

public class NamePointcutExample {
	public static void main(String[] args) {
		NameBean target = new NameBean();
		NameMatchMethodPointcut pc = new NameMatchMethodPointcut();
		pc.addMethodName("foo");
		pc.addMethodName("bar");
		Advisor advisor = new DefaultPointcutAdvisor(pc,new SimpleAdvice());
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(target);
		pf.addAdvisor(advisor);
		NameBean proxy = (NameBean)pf.getProxy();
		
		proxy.foo();
		proxy.foo(999);
		proxy.bar();
		proxy.yup();
	}
}


NamePointcutAdvisor

package test3;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;

public class NamePointcutUsingAdvisor {
	public static void main(String[] args) {
		NameBean target = new NameBean();
		
		NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(new SimpleAdvice());
		
		advisor.addMethodName("foo");
		advisor.addMethodName("bar");
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(target);
		pf.addAdvisor(advisor);
		NameBean proxy = (NameBean)pf.getProxy();
		proxy.foo();
		proxy.foo(999);
		proxy.bar();
		proxy.yup();
	}
}


RegexpPointcut

package test3;
public class RegexpBean {
	public void foo1() {
		System.out.println("foo1");
	}
	public void foo2() {
		System.out.println("foo2");
	}
	public void bar() {
		System.out.println("bar");
	}
}

package test3;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
public class RegexpPointcutExample {
	public static void main(String[] args) {
		RegexpBean target = new RegexpBean();
		JdkRegexpMethodPointcut pc = new JdkRegexpMethodPointcut();
		pc.setPattern(".*foo.*");
		Advisor advisor = new DefaultPointcutAdvisor(pc,new SimpleAdvice());
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(target);
		pf.addAdvisor(advisor);
		RegexpBean proxy = (RegexpBean)pf.getProxy();
		proxy.foo1();
		proxy.foo2();
		proxy.bar();
	}
}


ControlFlow Pointcut

package test4;

public class TestBean {
	public void foo() {
		System.out.println("foo()");
	}
}

package test4;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class SimpleBeforeAdvice implements MethodBeforeAdvice {
	public void before(Method method,Object[] args,Object target) throws Throwable
	{
		System.out.println("before method: "+method);
	}
}

package test4;
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.ControlFlowPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;

public class ControlFlowExample {

	public static void main(String[] args) {
		ControlFlowExample ex = new ControlFlowExample();
		ex.run();
	}
	public void run()
	{
		TestBean target = new TestBean();
		Pointcut pc = new ControlFlowPointcut(ControlFlowExample.class,"test");
		Advisor advisor = new DefaultPointcutAdvisor(pc,new SimpleBeforeAdvice());
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(target);
		pf.addAdvisor(advisor);
		TestBean proxy = (TestBean)pf.getProxy();
		System.out.println("Trying normal invoke");
		proxy.foo();
		System.out.println("Trying under ControlFlowExample.test()");
		test(proxy);
	}
	private void test(TestBean bean){
		bean.foo();
	}
}


ComposablePointcut

package test4;
public class SampleBean {
	public String getName()	{
		return "Rob Harrop";
	}
	public void setName(String abc)	{
	}
	public int getAge()
	{
		return 100;
	}
}

package test4;
import java.lang.reflect.Method;
import org.springframework.aop.Advisor;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.ComposablePointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcher;
public class ComposablePointcutExample {
	public static void main(String[] args) {
		SampleBean target = new SampleBean();
		ComposablePointcut pc = new ComposablePointcut(ClassFilter.TRUE,new GetterMethodMatcher());
		System.out.println("Test 1");
		SampleBean proxy = getProxy(pc,target);
		testInvoke(proxy);
		
		System.out.println("Test 2");
		pc.union(new SetterMethodMatcher());
		proxy = getProxy(pc,target);
		testInvoke(proxy);
		
		System.out.println("Test 3");
		pc.intersection(new GetAgeMethodMatcher());
		proxy = getProxy(pc,target);
		testInvoke(proxy);
	}
	
	private static SampleBean getProxy(ComposablePointcut pc,SampleBean target)
	{
		Advisor advisor = new DefaultPointcutAdvisor(pc,new SimpleBeforeAdvice());
		
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(target);
		pf.addAdvisor(advisor);
		
		return (SampleBean)pf.getProxy();
	}
	
	private static void testInvoke(SampleBean proxy)
	{
		proxy.getAge();
		proxy.getName();
		proxy.setName("Rob Harrop");
	}
	
	private static class GetterMethodMatcher extends StaticMethodMatcher{
		public boolean matches(Method method,Class cls)
		{
			return (method.getName().startsWith("get"));
		}
	}
	
	private static class GetAgeMethodMatcher extends StaticMethodMatcher{
		public boolean matches(Method method,Class cls)
		{
			return "getAge".equals(method.getName());
		}
	}
	
	private static class SetterMethodMatcher extends StaticMethodMatcher{
		public boolean matches(Method method,Class cls)
		{
			return (method.getName().startsWith("set"));
		}
	}
}


Introduction

package test4;
public class TargetBean {
	private String name;
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
}

package test4;
public interface IsModified {
	public boolean isModified();
}

package test4;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;

public class IsModifiedMixin extends DelegatingIntroductionInterceptor implements IsModified {
	private boolean isModified=false;
	private Map methodCache = new HashMap();
	public boolean isModified()
	{
		return isModified;
	}
	public Object invoke(MethodInvocation invocation) throws Throwable
	{
		if (!isModified)
		{
			if ((invocation.getMethod().getName().startsWith("set"))&&(invocation.getArguments().length==1))
			{
				
				Method getter = getGetter(invocation.getMethod());
				
				if (getter!=null)
				{
					Object newVal = invocation.getArguments()[0];
					Object oldVal = getter.invoke(invocation.getThis(),null);
					if ((newVal == null)&&(oldVal == null))
					{
						isModified = false;
					}else if ((newVal == null)&&(oldVal!=null))
					{
						isModified = true;
					}else if ((newVal!=null)&&(oldVal==null))
					{
						isModified = true;
					}else
					{
						isModified = (!newVal.equals(oldVal));
					}
				}
			}
		}
		return super.invoke(invocation);
	}

		private Method getGetter(Method setter)
		{
			Method getter = null;
			
			getter = (Method)methodCache.get(setter);
			
			if (getter!=null)
			{
				return getter;
			}
			
			String getterName = setter.getName().replaceFirst("set","get");
			try
			{
				getter = setter.getDeclaringClass().getMethod(getterName,null);
				synchronized(methodCache)
				{
					methodCache.put(setter,getter);
				}
				return getter;
			}catch(NoSuchMethodException ex)
			{
				return null;
			}
		}
}

package test4;
import org.springframework.aop.support.DefaultIntroductionAdvisor;
public class IsModifiedAdvisor extends DefaultIntroductionAdvisor{

	public IsModifiedAdvisor(){
		super(new IsModifiedMixin());
	}
}

package test4;

import org.springframework.aop.IntroductionAdvisor;
import org.springframework.aop.framework.ProxyFactory;

public class IntroductionExample {

	public static void main(String[] args) {
		TargetBean target = new TargetBean();
		target.setName("Rob Harrop");
		
		IntroductionAdvisor advisor = new IsModifiedAdvisor();
		
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(target);
		pf.addAdvisor(advisor);
		pf.setOptimize(true);
		
		TargetBean proxy = (TargetBean)pf.getProxy();
		IsModified proxyInterface = (IsModified)proxy;
		
		System.out.println("Is TargetBean?: "+(proxy instanceof TargetBean));
		System.out.println("Is IsModified?: "+(proxy instanceof IsModified));
		
		System.out.println("Has been Modified?: "+proxyInterface.isModified());
		proxy.setName("Rob Harrop");
		System.out.println("Has been Modified?: "+proxyInterface.isModified());
		proxy.setName("Joe Schmoe");
		System.out.println("Has been Modified?: "+proxyInterface.isModified());
	}
}




分享到:
评论

相关推荐

    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完整例子

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

    spring aop依赖jar包

    Spring AOP,全称Aspect-Oriented Programming(面向切面编程),是Spring框架的重要组成部分,它为Java应用程序提供了声明式的企业级服务,如事务管理、性能监控等。在Spring AOP中,我们可以通过定义切面(Aspect...

    spring-aop.jar各个版本

    spring-aop-1.1.1.jar spring-aop-1.2.6.jar spring-aop-1.2.9.jar spring-aop-2.0.2.jar spring-aop-2.0.6.jar spring-aop-2.0.7.jar spring-aop-2.0.8.jar spring-aop-2.0.jar spring-aop-2.5.1.jar spring-aop-...

    Spring Aop四个依赖的Jar包

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

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

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

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

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

    Spring AOP实现机制

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

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

    一、适合人群 1、具备一定Java编程基础,初级开发者 2、对springboot,mybatis,mysql有基本认识 3、对spring aop认识模糊的,不清楚如何实现Java 自定义注解的 ...4、spring boot,mybatis,druid,spring aop的使用

    基于注解实现SpringAop

    基于注解实现SpringAop基于注解实现SpringAop基于注解实现SpringAop

    spring aop 五个依赖jar

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

    spring AOP依赖三个jar包

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

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

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

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

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

    spring aop用到jar包.rar

    Spring AOP(面向切面编程)是Spring框架的重要组成部分,它提供了一种模块化和声明式的方式来处理系统中的交叉关注点,如日志、事务管理、性能监控等。在使用Spring AOP时,通常需要引入特定的jar包来支持其功能。...

    spring aop的demo

    Spring AOP(面向切面编程)是Spring框架的重要组成部分,它提供了一种在不修改源代码的情况下,对程序进行功能增强或横切关注点(如日志、事务管理、性能监控等)注入的方式。在本Demo中,我们将深入探讨Spring AOP...

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

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

    spring aop 学习笔记

    Spring AOP(面向切面编程)是Spring框架的重要组成部分,它提供了一种模块化和抽象化的方法来处理系统中的交叉关注点,如日志、事务管理、安全性等。本学习笔记将深入探讨Spring AOP的核心概念、工作原理以及实际...

Global site tag (gtag.js) - Google Analytics