`
free9277
  • 浏览: 106596 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Spring AOP配置与管理

阅读更多

1 准备例子

AOP为开发者定义了一组高层次的概念,用于表达横切关注点。在某个特定的执行点所执行的横切动作被封装在通知里(advice)里。为了更好地理解横切关注点,这里引入一个简单的计算器的例子。

首先,创建一个接口ArithmeticCalculator,处理算术计算。

package org.mahz.easyaop.calculator;

public interface ArithmeticCalculator {
	public double add(double a, double b);
	public double sub(double a, double b);
	public double mul(double a, double b);
	public double div(double a, double b);
}

接下来为每个计算器接口提供一个简单的实现。当这些方法为执行时println语句会给出提示。

package org.mahz.easyaop.calculator.impl;

import org.mahz.easyaop.calculator.ArithmeticCalculator;

public class ArithmeticCalculatorImpl implements ArithmeticCalculator {	
	
        private double result;
	
	public double add(double a, double b) {
		result = a + b;
		printResult(a, b, " + ");
		return result;
	}
	public double sub(double a, double b) {
		result = a - b;
		printResult(a, b, " - ");
		return result;
	}
	public double mul(double a, double b) {
		result =  a * b;
		printResult(a, b, " * ");
		return result;
	}
	public double div(double a, double b) {
                if(b == 0)
		    throw new IllegalArgumentException("Division by zero");
		result = a / b;
		printResult(a, b, " / ");
		return result;
	}
	public void printResult(double a, double b, String operation){
		System.out.println(a + operation + b + " = " + result);
	}
}

将计算机应用程序放到Spring IoC容器里运行。在SpringBean配置文件里声明这个计算器。

<bean id="arithmeticCalculator" class="org.mahz.easyaop.calculator.impl.ArithmeticCalculatorImpl" />

编写Client类来测试这个计算器的基本功能。

package org.mahz.easyaop.client;

import org.mahz.easyaop.calculator.ArithmeticCalculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean.xml");
		ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) context
				.getBean("arithmeticCalculator");
		double a = 4;
		double b = 0;
		arithmeticCalculator.add(a, b);
		arithmeticCalculator.sub(a, b);
		arithmeticCalculator.mul(a, b);
		arithmeticCalculator.div(a, b);
	}
}

2 实现过程

经典的Spring AOP支持4种类型的通知,它们分别作用于执行点的不同时间。不过,Spring AOP只支持方法执行。

前置通知(before advice):在方法执行之前。

返回通知(after returing advice):在方法执行之后。

异常通知(after throwing advice):在方法抛出异常之后。

环绕通知(around advice):围绕着方法执行。

2.1 前置通知

    前置通知在方法执行之前执行。可以通过实现MethodBeforeAdvice接口创建它。在before()方法,你能获取到目标方法的细节及其参数。

package org.mahz.easyaop.calculator.aop;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.springframework.aop.MethodBeforeAdvice;

public class LoggingBeforeAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target)
			throws Throwable {
		System.out.println("==========================================");
		System.out.println("============ Test " + method.getName()
				+ " Method =============");
		System.out.println("==========================================");
		System.out.println("The method " + method.getName() + "()begin with "
				+ Arrays.toString(args));
	}
}

2.2 返回通知

返回通知,记录方法的结束以及返回的结果。

package org.mahz.easyaop.calculator.aop;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class LoggingAfterAdvice implements AfterReturningAdvice {

	public void afterReturning(Object returnValue, Method method,
			Object[] args, Object target) throws Throwable {
		System.out.println("The Method " + method.getName() + "() ends with "
				+ returnValue);
	}
}

2.3 异常通知

对于异常通知类型来说,必须实现ThrowsAdvice接口。请注意,这个接口没有声明任何方法。这样就能够在不同的方法里处理不同类型的异常了,不过,每个处理方法的名称必须是afterThrowing。异常的类型由方法的参数类型指定。

package org.mahz.easyaop.calculator.aop;

import org.springframework.aop.ThrowsAdvice;

public class LoggingThrowsAdvice implements ThrowsAdvice {

	public void afterThrowing(IllegalArgumentException e) throws Throwable {
		System.out.println(e.getMessage());
	}
}
       准备好通知之后,下一步就是在计算器Bean上应用通知。首先,必须在IoC容器里声明该通知的实例。然后,使用Spring AOP提供的一个叫做自动代理创建器,可以为Bean自动创建代理。有了自动代理创建器,就不再需要使用ProxyFactoryBean手工地创建代理了。
<bean id="arithmeticCalculator"
		class="org.mahz.easyaop.calculator.impl.ArithmeticCalculatorImpl" />
<bean id="logginBeforeAdvice" class="org.mahz.easyaop.calculator.aop.LoggingBeforeAdvice" />
<bean id="logginAfterAdvice" class="org.mahz.easyaop.calculator.aop.LoggingAfterAdvice" />
<bean id="logginThrowsAdvice" class="org.mahz.easyaop.calculator.aop.LoggingThrowsAdvice" />
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
	<property name="beanNames">
		<list>
			<value>*Calculator</value>
		</list>
	</property>
	<property name="interceptorNames">
		<list>
			<value>logginBeforeAdvice</value>
			<value>logginAfterAdvice</value>
			<value>logginThrowsAdvice</value>
		</list>
	</property>
</bean>

2.4 执行结果

==========================================
============ Test add Method =============
==========================================
The method add()begin with [4.0, 0.0]
4.0 + 0.0 = 4.0
The Method add() ends with 4.0
==========================================
============ Test sub Method =============
==========================================
The method sub()begin with [4.0, 0.0]
4.0 - 0.0 = 4.0
The Method sub() ends with 4.0
==========================================
============ Test mul Method =============
==========================================
The method mul()begin with [4.0, 0.0]
4.0 * 0.0 = 0.0
The Method mul() ends with 0.0
==========================================
============ Test div Method =============
==========================================
The method div()begin with [4.0, 0.0]
Division by zero

3 总结

    关于第四种通知——环绕通知,可参考另一篇博文Spring AOP配置与管理的补充—环绕通知》。
2
2
分享到:
评论

相关推荐

    Spring AOP配置事务方法

    Spring AOP 提供了一种灵活的方式来实现事务管理,通过配置事务特性和事务管理切面来实现事务管理。 配置事务管理切面: 在 Spring AOP 中,事务管理切面是通过 `&lt;aop:config&gt;` 元素来配置的。该元素用于定义一个...

    springAop的配置实现

    在Spring XML配置文件中,我们可以定义以下元素来实现AOP配置: - `&lt;aop:config&gt;`:声明AOP配置。 - `&lt;aop:pointcut&gt;`:定义切入点表达式,例如`execution(* com.example.service.*.*(..))`表示匹配...

    使用Spring配置文件实现AOP

    在Spring框架中,面向切面编程(Aspect Oriented Programming,简称AOP)是一种强大的设计模式,它允许我们定义横切关注点,如日志、事务管理、权限检查等,然后将这些关注点与核心业务逻辑解耦。这篇教程将详细讲解...

    Spring之AOP配置文件详解

    通过上述的分析与解释,我们可以看出Spring AOP配置文件的核心在于定义不同的Bean以及它们之间的关系。这些Bean可以是具体的实现类也可以是代理工厂,通过这种方式,Spring AOP为我们提供了一种优雅的方式来管理横切...

    springAOP配置动态代理实现

    2. **注解配置**:Spring 2.5引入了基于注解的AOP配置,可以在切面类上使用@Aspect注解,@Before、@After、@AfterReturning、@AfterThrowing和@Around定义通知,@Pointcut定义切点。例如: ```java @Aspect ...

    spring aop jar 包

    在实际开发中,Spring AOP广泛应用于事务管理。例如,我们可以定义一个切面来处理所有数据库操作的事务,这样无需在每个业务方法中显式调用开始和提交事务,只需在切面中配置事务规则即可。 `aop-jar`这个压缩包...

    Spring AOP配置实例

    **Spring AOP配置实例** Spring AOP(Aspect Oriented Programming,面向切面编程)是Spring框架的核心组件之一,它提供了一种在不修改源代码的情况下,对程序进行功能增强的技术。AOP允许开发者定义“切面”,这些...

    简单spring aop 例子

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

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

    Spring支持两种AOP的实现方式:Spring AspectJ注解风格和Spring XML配置风格。使用AspectJ注解风格是最常见的,它允许开发者直接在方法上使用注解来定义切面。 Spring AOP中有五种不同类型的的通知(Advice): 1....

    Spring AOP完整例子

    在Spring XML配置中,我们可以使用`&lt;aop:config&gt;`元素来定义切点表达式,然后使用`&lt;aop:aspect&gt;`元素来声明切面,并将通知方法与切点关联起来。此外,还可以使用注解驱动的配置,通过`@EnableAspectJAutoProxy`注解...

    spring aop依赖jar包

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

    Spring AOP实现机制

    Spring AOP配置 Spring AOP的配置可以通过XML或注解方式进行: - **XML配置**: - 在`&lt;aop:config&gt;`标签内定义切面,`&lt;aop:pointcut&gt;`定义切入点,`&lt;aop:advisor&gt;`定义通知。 - `&lt;aop:aspect&gt;`标签用于定义完整...

    spring注解aop配置详解

    通过以上介绍,我们可以看到Spring的注解AOP配置是如何让代码更简洁、更易于理解和维护的。结合实际的项目需求,我们可以灵活地使用这些注解来实现各种企业级功能,如日志、事务控制等,从而提高代码的复用性和模块...

    springaop.zip

    在本示例中,"springaop.zip" 包含了一个使用XML配置的Spring AOP应用实例,可以直接运行,配合相关的博客文章学习效果更佳。 在Spring AOP中,我们首先需要了解几个核心概念: 1. **切面(Aspect)**:切面是关注...

    利用SPring AOP配置切面的一个例子

    本例中,我们关注的是如何利用Spring AOP配置一个简单的切面,该切面在`DukePerformer`类的`perform`方法执行前后,插入观众的行为,如找座位、关手机、鼓掌以及不满意的反应。通过这种方式,我们将这些行为抽象为...

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

    2. **轻量级**:与一些需要预编译器的AOP框架不同,Spring AOP无需特殊的工具或编译步骤即可使用。这种轻量级的特性使得Spring AOP更易于学习和集成。 3. **灵活的通知模型**:Spring AOP提供了多种类型的通知,...

    SpringAop xml方式配置通知

    AOP允许开发者定义“方面”,这些方面可以封装关注点,如日志、事务管理、性能度量等,将它们与业务逻辑解耦。在Spring框架中,AOP通过代理实现,可以使用XML配置或注解进行配置。本篇文章主要聚焦于Spring AOP的XML...

Global site tag (gtag.js) - Google Analytics