`
free9277
  • 浏览: 104782 次
  • 性别: 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的事务配置,方便开发应用和数据库的连接管理。

    Spring_aop源码

    Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向方面的编程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何对象支持 AOP。Spring AOP 模块为基于 Spring 的应用程序中的对象提供...

    springAop事务配置

    SpringAop配置事务管理,有两种配置方式。一种直接使用注解的方式,另外一种非注解

    Spring Aop之AspectJ注解配置实现日志管理的方法

    下面小编就为大家分享一篇Spring Aop之AspectJ注解配置实现日志管理的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

    基于java的企业级应用开发:Spring AOP简介.ppt

    support模块和SpEL(Spring Expression Language,Spring表达式语言)模块组成,具体介绍如下: Beans模块:提供了BeanFactory,是工厂模式的经典实现,Spring将管理对象称为Bean。 Core核心模块:提供了Spring框架...

    Spring AOP源码深度解析:掌握Java高级编程核心技术

    Spring AOP(面向切面编程)是Java高级编程中的重要组成部分,它允许程序员以声明的方式处理关注点(例如日志、事务管理等),而不是通过硬编码。本文深入分析了Spring AOP的实现机制,让读者能够更好地理解和应用这...

    Spring2.5和Hibernate3集成--学习spring aop ioc

    * 配置事务管理器 * 配置事务的传播特性 * 配置哪些类哪些方法使用事务 2.编写业务逻辑方法 * 继承HibernateDaoSupport类,使用this.HibernateTemplate这个类持久化数据 * HibernateTemplate是对session的轻...

    spring-aop-5.1.0.RELEASE.jar

    spring-**beans**-4.3.6.RELEASE.jar:所有应用都要用到的jar包,它包含访问配置文件.创建和管理bean以及进行Inversion ofContro(IOC )或者Dependency injection(DL)操作相关的所有类 spring-**cntext**-4.3.6....

    spring famework 基于xml配置aop示例

    spring aop示例,基于xml配置,使用maven管理

    Spring框架.ppt

    核心容器。...通过配置管理特性,可以很容易地使 Spring 框架管理的任何对象支持 AOP。Spring AOP 模块直接将面向方面编程的功能集成到Spring框架中。它为基于Spring 应用程序的对象提供了事务管理服务。

    Spring AOP demo

    基于注解与 XML 配置文件两种形式的 AOP demo。 基于 xml 配置文件的 aop 管理 ```xml &lt;!-- 配置切面的bean --&gt; &lt;bean id="loggingAspect" class="com.jas.aop.xml.LoggingAspect"/&gt; &lt;aop:config&gt; &lt;!...

    25个经典的Spring面试问答

    Spring Boot:熟悉Spring Boot,知道如何创建和管理Spring Boot项目,以及如何使用Spring Boot的自动配置功能。 Spring MVC:熟悉Spring MVC,知道如何使用它来构建Web应用程序。 Spring Data:熟悉Spring Data,...

    spring2.5学习PPT 传智博客

    05_配置Spring管理的bean的作用域 06_Spring管理的Bean的生命周期 07_编码剖析Spring依赖注入的原理 08_编码剖析Spring装配基本属性的原理 09_Spring如何装配各种集合类型的属性 10_使用构造器装配属性 11_用...

    spring4.3.2参考文档(英文)

    Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向方面的编程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何对象支持 AOP。Spring AOP 模块为基于 Spring 的应用程序中的对象提供...

    aop权限管理实例

    aop权限管理实例真实项目完整实例,有完整代码和配置及说明,spring版本是2.5,有需要的可以下载。上传只为分享

    基于Springboot+Mybatis+ SpringMvc+springsecrity+Redis完整网站后台管理系统

    spring security 全注解式的权限管理 动态配置权限,角色和资源,权限控制到按钮粒度 采用token进行权限校验,禁用session,未登录返回401,权限不足返回403 采用redis存储token及权限信息 内置功能: 用户管理...

    Spring 2.x配置详解

    Spring2.5提供了更灵活的配置方法, 本文档详细介绍了Spring2.x通过XML文件和Annotation如何配置Spring bean,事务管理配置,AOP的详细配置,以及其他Spring所提供支持的配置。

    spring中事物配置

    利用AOP定义声明式事物,配置事务管理器 , 配置事务的通知,配置事物代理,被注入的目标对象假如向拥有事务,必须有接口(AOP事务必须面向接口)

Global site tag (gtag.js) - Google Analytics