`
conkeyn
  • 浏览: 1519557 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

Spring AOP下嵌套一个代理

 
阅读更多

参考http://fyting.iteye.com/blog/109236总结整理。

Spring AOP的基本原理是使用代理实现切面,但是由于当前的Spring AOP(使用的Spring 3.2.9)不支持嵌套AOP的情况。话不多说,直接进入主题。

把代码贴上:

 

package spring.nest.aop;
public interface SomeService {  
    void someMethod();  
    void someInnerMethod();  
} 

 

package spring.nest.aop;

import org.springframework.context.ApplicationContext;

public class SomeServiceImpl implements SomeService, BeanSelfAware
{
	
	private SomeService someService;

	protected static ApplicationContext ctx;

	@RedisTransactional
	public void someMethod()
	{
		//使同一个代理对象可以支持嵌套的方法代理。
		someService.someInnerMethod();
		System.out.println("someMethod");
	}

	public void someInnerMethod()
	{
		System.out.println("someInnerMethod");
	}

	public void setSelf(Object proxyBean)
	{
		this.someService = (SomeService) proxyBean;
	}

}

 

 

 

package com.aa.redis.transaction.proxy;

/**
 * 使同一个bean在同一个代理对象下,可以切面两次
 * 
 * @author Zhongqing.Lin
 * @version 1.0.0
 * @since 2014年8月22日 上午9:28:51
 */
public interface BeanSelfAware
{

	void setSelf(Object proxyBean);
}

 

package com.aa.redis.transaction.proxy;

import java.lang.reflect.Method;

import com.zk.redis.transaction.annotation.RedisTransactional;

/**
 * 用于检查是否添加了@RedisTransactional标识
 * 
 * @author Zhongqing.Lin
 * @version 1.0.0
 * @since 2014年8月22日 上午9:32:36
 */
public class RedisTransactionalBeanUtils
{
	private RedisTransactionalBeanUtils()
	{

	}

	/**
	 * 检查是否添加了@RedisTransactional标识
	 * 
	 * @since 2014年8月21日 下午2:23:06
	 * @param bean bean
	 * @return true表示添加@RedisTransactional标识; false表示未添加@RedisTransactional标识;
	 */
	public static boolean checkRedisTransactionalBean(Object bean)
	{
		boolean bool = false;
		Method[] methods = bean.getClass().getDeclaredMethods();
		if (null != methods)
		{
			for (Method method : methods)
			{
				if (method.isAnnotationPresent(RedisTransactional.class))
				{
					bool = true;
					break;
				}
			}
		}
		return bool;
	}

}

 

package com.aa.redis.transaction.proxy;

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

/**
 * 使用Jdk的proxy实现代理
 * 
 * @author Zhongqing.Lin
 * @version 1.0.0
 * @param <T>
 * @since 2014年8月21日 下午1:47:38
 */
public class RedisTransactionalJdkProxy<T> implements RedisTransactionalProxy<T>, InvocationHandler
{
	// 目标对象   
	private T target;

	public T getTarget()
	{
		return this.target;
	}

	/**
	 * 构造方法
	 * 
	 * @param target 目标对象
	 */
	public RedisTransactionalJdkProxy(T target)
	{
		super();
		this.target = target;
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
	{
		// 在目标对象的方法执行之前简单的打印一下  
		System.out.println("------------------before  "+method.getName()+" ------------------");

		// 执行目标对象的方法  
		Object result = method.invoke(target, args);

		// 在目标对象的方法执行之后简单的打印一下  
		System.out.println("-------------------after  "+method.getName()+" ------------------");

		return result;
	}

	@SuppressWarnings("unchecked")
	public T getProxy()
	{
		return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}

}

 

package com.aa.redis.transaction.proxy;

/**
 * 代理对象接口
 * 
 * @author Zhongqing.Lin
 * @version 1.0.0
 * @param <T> 被代理的原始类型
 * @since 2014年8月22日 上午9:33:27
 */
public interface RedisTransactionalProxy<T>
{

	T getTarget();

}

 

package com.aa.redis.transaction.springframework.context.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import com.zk.redis.transaction.proxy.BeanSelfAware;
import com.zk.redis.transaction.proxy.RedisTransactionalBeanUtils;
import com.zk.redis.transaction.proxy.RedisTransactionalJdkProxy;

/**
 * 添加Redis事务代理对象的bean处理器
 * 
 * @author Zhongqing.Lin
 * @version 1.0.0
 * @since 2014年8月22日 上午9:29:51
 */
public class RedisTransactionalBeanProcessor implements BeanPostProcessor
{

	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
	{
		//如果实现
		if (bean instanceof BeanSelfAware)
		{
			((BeanSelfAware) bean).setSelf(bean);
		}
		if (RedisTransactionalBeanUtils.checkRedisTransactionalBean(bean))
		{
			System.out.println("inject proxy:" + bean.getClass());
			RedisTransactionalJdkProxy proxy = new RedisTransactionalJdkProxy(bean);
			return proxy.getProxy();
		}
		return bean;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
	{
		return bean;
	}

}

 

package com.aa.redis.transaction.springframework.context.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 为了扩展支持redis事务,又不让Redis事物不受到其他AOP影响,必须使用此增强类
 * 
 * @author Zhongqing.Lin
 * @version 1.0.0
 * @since 2014年8月22日 上午9:26:35
 */
public class ClassPathXmlApplicationContextRedisTransactional extends ClassPathXmlApplicationContext
{

	public ClassPathXmlApplicationContextRedisTransactional()
	{
	}

	/**
	 * Create a new ClassPathXmlApplicationContext for bean-style configuration.
	 * 
	 * @param parent the parent context
	 * @see #setConfigLocation
	 * @see #setConfigLocations
	 * @see #afterPropertiesSet()
	 */
	public ClassPathXmlApplicationContextRedisTransactional(ApplicationContext parent)
	{
		super(parent);
	}

	/**
	 * Create a new ClassPathXmlApplicationContext, loading the definitions
	 * from the given XML file and automatically refreshing the context.
	 * 
	 * @param configLocation resource location
	 * @throws BeansException if context creation failed
	 */
	public ClassPathXmlApplicationContextRedisTransactional(String configLocation) throws BeansException
	{
		this(new String[] {configLocation}, true, null);
	}

	/**
	 * Create a new ClassPathXmlApplicationContext, loading the definitions
	 * from the given XML files and automatically refreshing the context.
	 * 
	 * @param configLocations array of resource locations
	 * @throws BeansException if context creation failed
	 */
	public ClassPathXmlApplicationContextRedisTransactional(String... configLocations) throws BeansException
	{
		this(configLocations, true, null);
	}

	/**
	 * Create a new ClassPathXmlApplicationContext with the given parent,
	 * loading the definitions from the given XML files and automatically
	 * refreshing the context.
	 * 
	 * @param configLocations array of resource locations
	 * @param parent the parent context
	 * @throws BeansException if context creation failed
	 */
	public ClassPathXmlApplicationContextRedisTransactional(String[] configLocations, ApplicationContext parent) throws BeansException
	{
		this(configLocations, true, parent);
	}

	/**
	 * Create a new ClassPathXmlApplicationContext, loading the definitions
	 * from the given XML files.
	 * 
	 * @param configLocations array of resource locations
	 * @param refresh whether to automatically refresh the context,
	 * loading all bean definitions and creating all singletons.
	 * Alternatively, call refresh manually after further configuring the context.
	 * @throws BeansException if context creation failed
	 * @see #refresh()
	 */
	public ClassPathXmlApplicationContextRedisTransactional(String[] configLocations, boolean refresh) throws BeansException
	{
		this(configLocations, refresh, null);
	}

	/**
	 * Create a new ClassPathXmlApplicationContext with the given parent,
	 * loading the definitions from the given XML files.
	 * 
	 * @param configLocations array of resource locations
	 * @param refresh whether to automatically refresh the context,
	 * loading all bean definitions and creating all singletons.
	 * Alternatively, call refresh manually after further configuring the context.
	 * @param parent the parent context
	 * @throws BeansException if context creation failed
	 * @see #refresh()
	 */
	public ClassPathXmlApplicationContextRedisTransactional(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException
	{

		super(parent);
		setConfigLocations(configLocations);
		if (refresh)
		{
			refresh();
		}
	}

	/**
	 * Create a new ClassPathXmlApplicationContext, loading the definitions
	 * from the given XML file and automatically refreshing the context.
	 * <p>
	 * This is a convenience method to load class path resources relative to a given Class. For full flexibility, consider using a GenericApplicationContext with an XmlBeanDefinitionReader and a ClassPathResource argument.
	 * 
	 * @param path relative (or absolute) path within the class path
	 * @param clazz the class to load resources with (basis for the given paths)
	 * @throws BeansException if context creation failed
	 * @see org.springframework.core.io.ClassPathResource#ClassPathResource(String, Class)
	 * @see org.springframework.context.support.GenericApplicationContext
	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
	 */
	public ClassPathXmlApplicationContextRedisTransactional(String path, Class clazz) throws BeansException
	{
		this(new String[] {path}, clazz);
	}

	/**
	 * Create a new ClassPathXmlApplicationContext, loading the definitions
	 * from the given XML files and automatically refreshing the context.
	 * 
	 * @param paths array of relative (or absolute) paths within the class path
	 * @param clazz the class to load resources with (basis for the given paths)
	 * @throws BeansException if context creation failed
	 * @see org.springframework.core.io.ClassPathResource#ClassPathResource(String, Class)
	 * @see org.springframework.context.support.GenericApplicationContext
	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
	 */
	public ClassPathXmlApplicationContextRedisTransactional(String[] paths, Class clazz) throws BeansException
	{
		this(paths, clazz, null);
	}

	/**
	 * Create a new ClassPathXmlApplicationContext with the given parent,
	 * loading the definitions from the given XML files and automatically
	 * refreshing the context.
	 * 
	 * @param paths array of relative (or absolute) paths within the class path
	 * @param clazz the class to load resources with (basis for the given paths)
	 * @param parent the parent context
	 * @throws BeansException if context creation failed
	 * @see org.springframework.core.io.ClassPathResource#ClassPathResource(String, Class)
	 * @see org.springframework.context.support.GenericApplicationContext
	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
	 */
	public ClassPathXmlApplicationContextRedisTransactional(String[] paths, Class clazz, ApplicationContext parent) throws BeansException
	{
		super(paths, clazz, parent);
	}

	@Override
        //继承函数,并添加自定义代码。
	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
	{
		super.postProcessBeanFactory(beanFactory);
                //添加代理的bean处理器
		beanFactory.addBeanPostProcessor(new RedisTransactionalBeanProcessor());
	}

}

 

<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.5.xsd  
            http://www.springframework.org/schema/aop  
            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
            ">
		<bean id="debugInterceptor" class="org.springframework.aop.interceptor.DebugInterceptor" />

		<bean id="someServiceTarget" class="spring.nest.aop.SomeServiceImpl" />

		<bean id="someService" class="org.springframework.aop.framework.ProxyFactoryBean">
			<property name="proxyInterfaces">
				<value>spring.nest.aop.SomeService</value>
			</property>
			<property name="target">
				<ref local="someServiceTarget" />
			</property>
			<property name="interceptorNames">
				<list>
					<value>someAdvisor</value>
				</list>
			</property>
		</bean>

		<bean id="someAdvisor"
			class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
			<property name="advice">
				<ref local="debugInterceptor" />
			</property>
			<property name="patterns">
				<list>
					<value>spring\.nest\.aop\.SomeService\.someMethod</value>
					<value>spring\.nest\.aop\.SomeService\.someInnerMethod</value>
				</list>
			</property>
		</bean>

	</beans>  

 

 

 

package com.aa.redis.transaction.test;

import org.springframework.context.ApplicationContext;

import spring.nest.aop.SomeService;

public class SomeServiceTest
{
	public static void main(String[] args)
	{
		String[] paths = {"classpath:spring/nest/aop/test/spring.xml"};
		ApplicationContext ctx = new ClassPathXmlApplicationContextRedisTransactional(paths);
		SomeService someService = (SomeService) ctx.getBean("someService");
		someService.someMethod();
		someService.someInnerMethod();
	}
}

 =====================================

 

在web环境中的配置方式:

service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    
    <bean id="someService" class="spring.nest.aop.SomeServiceImpl" />
    
</beans>

 

beanRefContext.xml,配置的自定义ClassPathXmlApplicationContext主要是为了让web.xml中的org.springframework.web.context.ContextLoaderListener在初始化是能够复制bean处理器(BeanPostProcessor)

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <context:annotation-config/>
    <!-- <context:spring-configured/> -->
        <!-- 使这个ApplicationContext作为一个父ApplicationContext存在,以便web.xml中的子ApplicationContext复制父ApplicationContext的属性值。 -->
	<bean id="businessBeanFactory"
		class="spring.nest.aop.test.ClassPathXmlApplicationContextRedisTransactional">
		<constructor-arg>
		  <list>
		      <value>classpath:config/service.xml</value>
		  </list>
		</constructor-arg>
	</bean>
</beans>

 

 

web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<context-param>
		<param-name>locatorFactorySelector</param-name>
		<param-value>classpath:config/beanRefContext.xml</param-value>
	</context-param>
	<context-param>
		<param-name>parentContextKey</param-name>
		<param-value>businessBeanFactory</param-value>
	</context-param>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/applicationContext.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

 

 

 

 

 

 

分享到:
评论

相关推荐

    spring-nested-aop.zip_aop_spring aop

    在这个名为"spring-nested-aop.zip"的压缩包中,包含了一个关于Spring AOP的嵌套事务处理的示例程序。这通常涉及到在一个事务方法内部调用另一个事务方法的情况,两个方法都需要在同一事务范围内运行,以便确保数据...

    Spring AOP之基于Schema配置总结与案例

    在Spring XML配置中,使用`&lt;aop:aspect&gt;`标签定义一个切面,然后在其中嵌套通知标签。 下面是一个简单的基于Schema配置的Spring AOP例子: ```xml &lt;aop:config&gt; &lt;aop:aspect id="loggingAspect" ref="logging...

    AOP实现自我调用的事物嵌套问题

    Spring使用代理模式来实现AOP,根据配置(如@Transactional注解)为被代理对象创建一个代理对象。当调用被代理对象的方法时,实际上是调用了代理对象的方法,这样就能在方法执行前后插入事务控制代码。然而,如果一...

    Spring AOP管理Hibernate事务(TransactionInSpringAOP)

    3. **AOP代理**:Spring会创建一个代理对象来包围业务逻辑,当方法调用时,代理会检查是否有@Transactional注解,并根据注解的属性启动一个新的事务或参与到现有的事务中。 4. **事务传播行为**:比如PROPAGATION_...

    spring隔离级别和aop基础.md

    7. **PROPAGATION_NESTED**:如果当前存在事务,则创建一个事务作为当前事务的嵌套事务;如果当前没有事务,则行为类似于PROPAGATION_REQUIRED。 ### Spring AOP 面向切面编程 #### AOP 概念 面向切面编程 ...

    SSM整合-用springaop-demo01实现了注解AOP,SSM-MybatisOneForOne-demo01实现了

    在这个场景下,我们有两个演示项目:`springaop-demo01` 和 `SSM-MybatisOneForOne-demo01`。 1. **Spring AOP(面向切面编程)**: - **AOP概念**:AOP是Spring框架的核心特性之一,它允许程序员定义“切面”,...

    springAop事务配置

    - **@Transactional**:这是Spring提供的核心注解,用于标记在一个方法或类上开启事务。当被注解的方法执行时,Spring会自动为其创建并管理事务。 - **属性详解**: - `value`:指定事务管理器的bean名,如果不...

    Spring基础.pdf

    AOP是Spring提供的另一种重要特性,它允许开发者在不修改原始代码的情况下,通过代理的方式在原有功能基础上进行增强。AOP的实现基于动态代理技术,动态代理可以在程序运行时为目标对象创建代理对象,代理对象通常会...

    Spring2.x对事务的管理(AOP)

    即使当前存在事务也会挂起)、`NOT_SUPPORTED`(永不启动事务,如果当前存在事务,就挂起)、`NEVER`(永不启动事务,如果当前存在事务,则抛出异常)、`NESTED`(如果当前存在事务,则在一个嵌套事务中运行,否则...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.1.3. Spring的AOP代理 6.2. @AspectJ支持 6.2.1. 启用@AspectJ支持 6.2.2. 声明一个切面 6.2.3. 声明一个切入点(pointcut) 6.2.3.1. 切入点指定者的支持 6.2.3.2. 合并切入点表达式 6.2.3.3. 共享常见的切入点...

    Spring学习思维笔记.pdf

    当调用一个接口方法时,JDK动态代理会在运行时创建一个代理类,该类继承了Proxy类并实现了被代理的接口。通过Proxy类中的newProxyInstance方法,可以生成代理对象,其内部实现依赖于实现了InvocationHandler接口的...

    Spring 2.0 开发参考手册

    6.1.3. Spring的AOP代理 6.2. @AspectJ支持 6.2.1. 启用@AspectJ支持 6.2.2. 声明一个切面 6.2.3. 声明一个切入点(pointcut) 6.2.4. 声明通知 6.2.5. 引入(Introductions) 6.2.6. 切面实例化模型 6.2.7....

    SpringAOP事务配置语法及实现过程详解

    以下是一个使用`DataSourceTransactionManager`的配置示例: ```xml &lt;bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt; ``` 在这里,`dataSource`引用是数据源...

    Spring 开发参考手册

    - **AOP 代理** (AOP Proxy): 实现 AOP 的关键,Spring 使用 JDK 动态代理或 CGLIB 代理来实现。 #### 六、属性编辑器、数据绑定、校验与 BeanWrapper - **属性编辑器** (Property Editor): 用于转换不可直接转换...

    深入理解Spring声明式事务:源码分析与应用实践

    Spring会创建一个代理对象来包裹被注解的方法,当调用这些方法时,实际上是在调用代理对象,从而实现事务的自动化管理。 在事务管理过程中,Spring通过`@EnableAspectJAutoProxy`注解启用AOP代理。AOP代理可以是JDK...

    Java AOP 公共异常处理,一个没有try的项目。.zip

    在"Java AOP 公共异常处理,一个没有try的项目"中,我们可以探讨如何利用AOP实现优雅的异常管理,避免在每个方法中都嵌套冗余的try-catch语句。 AOP的核心概念包括切面(Aspect)、连接点(Join Point)、通知...

    Spring中文帮助文档

    9.9.1. 对一个特定的 DataSource 使用了错误的事务管理器 9.10. 更多的资源 10. DAO支持 10.1. 简介 10.2. 一致的异常层次 10.3. 一致的DAO支持抽象类 11. 使用JDBC进行数据访问 11.1. 简介 11.1.1. 选择一...

    通用的报表缓存设计(Spring AOP + Redis)

    然后,创建一个名为`RedisProcess`的切面类,它使用了Spring的`@Aspect`和`@Component`注解,表示这是一个AOP组件。在`RedisProcess`类中,注入了`RedisTemplate`以操作Redis,并定义了一个`pointcutMethod()`方法...

Global site tag (gtag.js) - Google Analytics