`
tuoxinquyu
  • 浏览: 14157 次
  • 性别: Icon_minigender_2
  • 来自: 郑州
社区版块
存档分类
最新评论

Spring AOP Example – Pointcut , Advisor

 
阅读更多

In last Spring AOP advice examples, the entire methods of a class are intercepted automatically. But for most cases, you may just need a way to intercept only one or two methods, this is what ‘Pointcut’ come for. It allow you to intercept a method by it’s method name. In addition, a ‘Pointcut’ must be associated with an ‘Advisor’.

In Spring AOP, comes with three very technical terms – Advices, Pointcut , Advisor, put it in unofficial way…

  • Advice – Indicate the action to take either before or after the method execution.
  • Pointcut – Indicate which method should be intercept, by method name or regular expression pattern.
  • Advisor – Group ‘Advice’ and ‘Pointcut’ into a single unit, and pass it to a proxy factory object.

Review last Spring AOP advice examples again.

File : CustomerService.java

package com.mkyong.customer.services;
 
public class CustomerService
{
	private String name;
	private String url;
 
	public void setName(String name) {
		this.name = name;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public void printName(){
		System.out.println("Customer name : " + this.name);
	}
 
	public void printURL(){
		System.out.println("Customer website : " + this.url);
	}
 
	public void printThrowException(){
		throw new IllegalArgumentException();
	}
 
}

File : Spring-Customer.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="name" value="Yong Mook Kim" />
		<property name="url" value="http://www.mkyong.com" />
	</bean>
 
	<bean id="hijackAroundMethodBeanAdvice" class="com.mkyong.aop.HijackAroundMethod" />
 
	<bean id="customerServiceProxy" 
                class="org.springframework.aop.framework.ProxyFactoryBean">
 
		<property name="target" ref="customerService" />
 
		<property name="interceptorNames">
			<list>
				<value>hijackAroundMethodBeanAdvice</value>
			</list>
		</property>
	</bean>
</beans>

File : HijackAroundMethod.java

package com.mkyong.aop;
 
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
 
public class HijackAroundMethod implements MethodInterceptor {
	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
 
		System.out.println("Method name : "
				+ methodInvocation.getMethod().getName());
		System.out.println("Method arguments : "
				+ Arrays.toString(methodInvocation.getArguments()));
 
		System.out.println("HijackAroundMethod : Before method hijacked!");
 
		try {
			Object result = methodInvocation.proceed();
			System.out.println("HijackAroundMethod : Before after hijacked!");
 
			return result;
 
		} catch (IllegalArgumentException e) {
 
			System.out.println("HijackAroundMethod : Throw exception hijacked!");
			throw e;
		}
	}
}

Run it

package com.mkyong.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.mkyong.customer.services.CustomerService;
 
public class App {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				new String[] { "Spring-Customer.xml" });
 
		CustomerService cust = (CustomerService) appContext
				.getBean("customerServiceProxy");
 
		System.out.println("*************************");
		cust.printName();
		System.out.println("*************************");
		cust.printURL();
		System.out.println("*************************");
		try {
			cust.printThrowException();
		} catch (Exception e) {
		}
	}
}

Output

*************************
Method name : printName
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer name : Yong Mook Kim
HijackAroundMethod : Before after hijacked!
*************************
Method name : printURL
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer website : http://www.mkyong.com
HijackAroundMethod : Before after hijacked!
*************************
Method name : printThrowException
Method arguments : []
HijackAroundMethod : Before method hijacked!
HijackAroundMethod : Throw exception hijacked!

The entire methods of customer service class are intercepted. Later, we show you how to use “pointcuts” to intercept only printName() method.

Pointcuts example

You can match the method via following two ways :

  1. Name match
  2. Regular repression match

1. Pointcuts – Name match example

Intercept a printName() method via ‘pointcut’ and ‘advisor’. Create a NameMatchMethodPointcut pointcut bean, and put the method name you want to intercept in the ‘mappedName‘ property value.

	<bean id="customerPointcut"
        class="org.springframework.aop.support.NameMatchMethodPointcut">
		<property name="mappedName" value="printName" />
	</bean>

Create a DefaultPointcutAdvisor advisor bean, and associate both advice and pointcut.

	<bean id="customerAdvisor"
		class="org.springframework.aop.support.DefaultPointcutAdvisor">
		<property name="pointcut" ref="customerPointcut" />
		<property name="advice" ref="hijackAroundMethodBeanAdvice" />
	</bean>

Replace the proxy’s ‘interceptorNames’ to ‘customerAdvisor’ (it was ‘hijackAroundMethodBeanAdvice’).

	<bean id="customerServiceProxy"
		class="org.springframework.aop.framework.ProxyFactoryBean">
 
		<property name="target" ref="customerService" />
 
		<property name="interceptorNames">
			<list>
				<value>customerAdvisor</value>
			</list>
		</property>
	</bean>

Full bean configuration file

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="name" value="Yong Mook Kim" />
		<property name="url" value="http://www.mkyong.com" />
	</bean>
 
	<bean id="hijackAroundMethodBeanAdvice" class="com.mkyong.aop.HijackAroundMethod" />
 
	<bean id="customerServiceProxy" 
                class="org.springframework.aop.framework.ProxyFactoryBean">
 
		<property name="target" ref="customerService" />
 
		<property name="interceptorNames">
			<list>
				<value>customerAdvisor</value>
			</list>
		</property>
	</bean>
 
	<bean id="customerPointcut" 
                class="org.springframework.aop.support.NameMatchMethodPointcut">
		<property name="mappedName" value="printName" />
	</bean>
 
	<bean id="customerAdvisor" 
                 class="org.springframework.aop.support.DefaultPointcutAdvisor">
		<property name="pointcut" ref="customerPointcut" />
		<property name="advice" ref="hijackAroundMethodBeanAdvice" />
	</bean>
 
</beans>

Run it again, output

*************************
Method name : printName
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer name : Yong Mook Kim
HijackAroundMethod : Before after hijacked!
*************************
Customer website : http://www.mkyong.com
*************************

Now, you only intercept the printName() method.

PointcutAdvisor
Spring comes with PointcutAdvisor class to save your work to declare advisor and pointcut into different beans, you can use NameMatchMethodPointcutAdvisor to combine both into a single bean.

 

	<bean id="customerAdvisor"
		class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
 
		<property name="mappedName" value="printName" />
		<property name="advice" ref="hijackAroundMethodBeanAdvice" />
 
	</bean>

2. Pointcut – Regular expression example

You can also match the method’s name by using regular expression pointcut – RegexpMethodPointcutAdvisor.

	<bean id="customerAdvisor"
		class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
		<property name="patterns">
			<list>
				<value>.*URL.*</value>
			</list>
		</property>
 
		<property name="advice" ref="hijackAroundMethodBeanAdvice" />
	</bean>

Now, it intercepts the method which has words ‘URL’ within the method name. In practice, you can use it to manage DAO layer, where you can declare “.*DAO.*” to intercept all your DAO classes to support transaction.

 

文章来自:http://www.mkyong.com/spring/spring-aop-example-pointcut-advisor/

分享到:
评论

相关推荐

    springAop的配置实现

    - `&lt;aop:advisor&gt;`:定义通知和切入点的关联,指定何时何地执行通知。 - `&lt;aop:aspect&gt;`:定义切面,包括其通知和切入点。 - `&lt;aop:before&gt;`、`&lt;aop:after&gt;`、`&lt;aop:around&gt;`等:分别用于定义不同类型的通知。 **5....

    springAOP配置动态代理实现

    1. **XML配置**:在Spring的配置文件中,可以通过&lt;aop:config&gt;标签来定义切面,&lt;aop:pointcut&gt;定义切点,&lt;aop:advisor&gt;或&lt;aop:aspect&gt;定义通知。例如: ```xml &lt;aop:config&gt; &lt;aop:pointcut id="myPointcut" ...

    spring AOP入门教程

    - **SpringAOP.avi**:可能是一个视频教程,详细讲解了Spring AOP的概念和实践。 - **SpringAOP.doc**:可能是文档教程,包含了详细的步骤和示例代码。 - **SpringAOP_src.rar**:源代码示例,供你参考和实践。 - **...

    Spring AOP 入门作者:廖雪峰

    例如,可以定义一个名为`LoggingAdvisor`的`Advisor`,其`Pointcut`表达式为`execution(* com.crackj2ee.example.spring.MyServiceBean.*(..))`,表示所有`MyServiceBean`的公共方法都应被增强,而`Advice`则负责在...

    spring aop管理xml版

    - `&lt;aop:advisor&gt;`:可以包含一个通知和一个切入点,是更细粒度的配置单元。 在实际应用中,我们会在`&lt;bean&gt;`元素中定义切面类,并在`&lt;aop:config&gt;`中通过`&lt;aop:aspect&gt;`元素引用它,然后定义相应的通知和切入点。...

    用xml配置的方式进行SpringAOP开发

    2. **定义Advisor**:Advisor是Spring AOP的核心组件,它包含一个切点表达式和一个通知。在XML配置中,我们可以创建一个Advisor Bean来指定切点和通知: ```xml &lt;bean id="loggingAdvisor" class="org.spring...

    spring aop xml 实例

    &lt;aop:advisor advice-ref="myAdvice" pointcut-ref="myPointcut"/&gt; &lt;/aop:config&gt; &lt;aop:aspect id="myAspect"&gt; &lt;!-- 定义通知 --&gt; &lt;aop:before method="beforeMethod" pointcut-ref="myPointcut"/&gt; &lt;aop:after-...

    使用Spring配置文件实现AOP

    在Spring的XML配置文件中,我们可以创建一个`&lt;aop:config&gt;`元素,并在其内部定义`&lt;aop:advisor&gt;`来创建Advisor。Advisor的`advice-ref`属性用于指定通知bean的ID,`pointcut-ref`属性用于指定切点bean的ID。 2. ...

    SPRING:aspect和advisor区别

    本文旨在深入探讨Spring AOP中的两个核心概念:`Aspect`与`Advisor`的区别,并通过具体的配置示例帮助读者更好地理解和应用这些概念。 #### 二、Aspect的概念解析 1. **定义**: - `Aspect`在Spring AOP中被称为...

    Spring基础:Spring AOP简单使用

    - **XML配置**:在Spring的配置文件中,可以使用&lt;aop:config&gt;标签来定义切面,&lt;aop:pointcut&gt;定义切点,&lt;aop:advisor&gt;定义通知,&lt;aop:aspect&gt;将切点和通知关联起来。 - **注解配置**:Spring 2.5引入了基于注解的...

    spring Aop文档

    Spring AOP的核心在于`Advisor`和`Advice`的实现,这些类通过`ProxyFactoryBean`或`CglibAopProxy`等代理工厂类生成代理对象。 1. **`Advisor`**:封装了`Pointcut`和`Advice`,是AOP的最小单元。 2. **`...

    SpringAOP依赖包

    其中,`org.springframework.aop`包下提供了各种接口和类,如`AspectJExpressionPointcut`用于表达式匹配,`Advisor`代表增强策略,`Pointcut`定义了通知(Advice)应用的时机。 2. **spring-beans.jar**:虽然主要...

    SpringAOP简单项目实现

    总结,这个"SpringAOP简单项目实现"涵盖了Spring AOP的基础知识,包括切面、通知、切入点的定义与配置,以及如何在实际项目中使用Maven进行构建和依赖管理。对于初学者来说,这是一个很好的实践案例,能够帮助他们...

    SpringAOP1.zip

    本文将基于"LYFspringAOP系列:自己写的springAOP例子"进行深入讲解。 首先,了解AOP的基本概念。AOP是一种编程范式,旨在解决程序中分散的、与业务逻辑不直接相关的部分,如日志记录、事务管理、性能监控等。通过...

    理解Spring AOP实现与思想 案例代码

    - **XML配置**:在Spring的配置文件中,可以使用`&lt;aop:config&gt;`标签定义切面,`&lt;aop:pointcut&gt;`定义切入点,`&lt;aop:advisor&gt;`定义通知。 - **注解配置**:使用`@Aspect`定义切面,`@Pointcut`定义切入点,`@Before`...

    应用Spring AOP(二)-------通过Advisor指定切入点

    在本篇博文中,我们将深入探讨Spring AOP(面向切面编程)的使用,特别是如何通过Advisor指定切入点。Spring AOP是Spring框架的核心组件之一,它允许我们在不修改业务代码的情况下,实现对程序运行时行为的拦截和...

    Spring AOP 类图

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

    spring AOP 例子参考

    2. **基于XML配置的AOP**:在Spring配置文件中定义切面和通知,使用 `&lt;aop:config&gt;` 和 `&lt;aop:advisor&gt;` 等元素。 **三、实战示例** 1. **创建切面类**:首先,创建一个包含通知方法的切面类,例如: ```java @...

Global site tag (gtag.js) - Google Analytics