Java的Spring框架下的AOP编程模式示例_java

Spring框架的关键组件是面向方面编程(AOP)框架。面向方面的编程不仅打破程序逻辑分成不同的部分称为所谓的担忧。跨越多个点的应用程序的功能被称为横切关注点和这些横切关注点是从应用程序的业务逻辑概念上区分开来。还有像日志记录,审计,声明性事务,安全性和高速缓存等方面的各种常见的好例子

模块化的OOP中的关键单元是类,而在AOP中模块化的单元则是切面。依赖注入可以帮助你从对方解耦应用程序对象和AOP可以帮助你从他们影响的对象分离横切关注点。 AOP是一样的编程语言如Perl,.NET,Java和其他触发器。

Spring AOP模块提供了拦截器拦截的应用程序,例如,执行一个方法时,可以之前或之后执行的方法添加额外的功能。

AOP术语:
在我们开始使用AOP之前,先熟悉AOP的概念和术语。这些条款是不特定于Spring,问题都是有关AOP。
建议的类型
Spring方面可以用5种下面提到的建议:

自定义方面实现

Spring基于XML模式的AOP
需要如下所述导入Spring AOP架构:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <!-- bean definition & AOP specific configuration -->

</beans>

还需要在以下应用程序CLASSPATH中的AspectJ库。这些库可以在AspectJ的安装'lib'目录可用,可以从互联网上下载它们。

  • aspectjrt.jar
  • aspectjweaver.jar
  • aspectj.jar

声明一个切面
一个方面是使用<aop:aspect>元素中声明,并且支持bean是使用ref属性如下参考:

<aop:config>
  <aop:aspect id="myAspect" ref="aBean">
  ...
  </aop:aspect>
</aop:config>

<bean id="aBean" class="...">
...
</bean>

这里的“aBean”将配置和依赖注入,就像任何其他的Spring bean,我们已经在前面的章节看到。

声明一个切入点
一个切入点有助于确定与不同要执行的连接点的利息(即方法)。同时与XML架构基础的配置工作,切入点将被定义如下:

<aop:config>
  <aop:aspect id="myAspect" ref="aBean">

  <aop:pointcut id="businessService"
   expression="execution(* com.xyz.myapp.service.*.*(..))"/>
  ...
  </aop:aspect>
</aop:config>

<bean id="aBean" class="...">
...
</bean>

下面的示例定义一个名为'的businessService“切入点将匹配可用的软件包com.yiibai下执行getName()方法在Student类:

<aop:config>
  <aop:aspect id="myAspect" ref="aBean">

  <aop:pointcut id="businessService"
   expression="execution(* com.yiibai.Student.getName(..))"/>
  ...
  </aop:aspect>
</aop:config>

<bean id="aBean" class="...">
...
</bean>

声明建议
可以声明任意五个建议的使用<aop:{ADVICE NAME}>元素下面给出一个<aop:aspect>内:

<aop:config>
  <aop:aspect id="myAspect" ref="aBean">
   <aop:pointcut id="businessService"
     expression="execution(* com.xyz.myapp.service.*.*(..))"/>

   <!-- a before advice definition -->
   <aop:before pointcut-ref="businessService"
     method="doRequiredTask"/>

   <!-- an after advice definition -->
   <aop:after pointcut-ref="businessService"
     method="doRequiredTask"/>

   <!-- an after-returning advice definition -->
   <!--The doRequiredTask method must have parameter named retVal -->
   <aop:after-returning pointcut-ref="businessService"
     returning="retVal"
     method="doRequiredTask"/>

   <!-- an after-throwing advice definition -->
   <!--The doRequiredTask method must have parameter named ex -->
   <aop:after-throwing pointcut-ref="businessService"
     throwing="ex"
     method="doRequiredTask"/>

   <!-- an around advice definition -->
   <aop:around pointcut-ref="businessService"
     method="doRequiredTask"/>
  ...
  </aop:aspect>
</aop:config>

<bean id="aBean" class="...">
...
</bean>

可以使用相同的doRequiredTask或不同的方法针对不同的建议。这些方法将被定义为纵横模块的一部分。

基于XML模式的AOP例
要理解上述关系到XML模式的AOP提到的概念,让我们写这将实现几个建议的一个例子。

这里是Logging.java文件的内容。这实际上是纵横模块的一个示例,它定义的方法被调用的各个点。

package com.yiibai;

public class Logging {

  /**
  * This is the method which I would like to execute
  * before a selected method execution.
  */
  public void beforeAdvice(){
   System.out.println("Going to setup student profile.");
  }

  /**
  * This is the method which I would like to execute
  * after a selected method execution.
  */
  public void afterAdvice(){
   System.out.println("Student profile has been setup.");
  }

  /**
  * This is the method which I would like to execute
  * when any method returns.
  */
  public void afterReturningAdvice(Object retVal){
   System.out.println("Returning:" + retVal.toString() );
  }

  /**
  * This is the method which I would like to execute
  * if there is an exception raised.
  */
  public void AfterThrowingAdvice(IllegalArgumentException ex){
   System.out.println("There has been an exception: " + ex.toString());
  }

}

以下是Student.java文件的内容:

package com.yiibai;

public class Student {
  private Integer age;
  private String name;

  public void setAge(Integer age) {
   this.age = age;
  }
  public Integer getAge() {
  System.out.println("Age : " + age );
   return age;
  }

  public void setName(String name) {
   this.name = name;
  }
  public String getName() {
   System.out.println("Name : " + name );
   return name;
  }

  public void printThrowException(){
  System.out.println("Exception raised");
    throw new IllegalArgumentException();
  }
}

以下是MainApp.java文件的内容:

package com.yiibai;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
  public static void main(String[] args) {
   ApplicationContext context =
       new ClassPathXmlApplicationContext("Beans.xml");

   Student student = (Student) context.getBean("student");

   student.getName();
   student.getAge();

   student.printThrowException();
  }
}

以下是配置文件beans.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <aop:config>
   <aop:aspect id="log" ref="logging">
     <aop:pointcut id="selectAll"
     expression="execution(* com.yiibai.*.*(..))"/>
     <aop:before pointcut-ref="selectAll" method="beforeAdvice"/>
     <aop:after pointcut-ref="selectAll" method="afterAdvice"/>
     <aop:after-returning pointcut-ref="selectAll"
               returning="retVal"
               method="afterReturningAdvice"/>
     <aop:after-throwing pointcut-ref="selectAll"
               throwing="ex"
               method="AfterThrowingAdvice"/>
   </aop:aspect>
  </aop:config>

  <!-- Definition for student bean -->
  <bean id="student" class="com.yiibai.Student">
   <property name="name" value="Zara" />
   <property name="age" value="11"/>
  </bean>

  <!-- Definition for logging aspect -->
  <bean id="logging" class="com.yiibai.Logging"/> 

</beans>

创建源代码和bean配置文件完成后,让我们运行应用程序。如果一切顺利,这将打印以下信息:

Going to setup student profile.
Name : Zara
Student profile has been setup.
Returning:Zara
Going to setup student profile.
Age : 11
Student profile has been setup.
Returning:11
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
.....
other exception content

解释一下,上面定义<aop:pointcut>选择所有的包com.yiibai下定义的方法。让我们假设,想有一个特定的方法之前或之后执行意见,可以定义切入点与实际的类和方法的名称取代星号(*)的切入点定义来缩小执行。下面是修改后的XML配置文件,以显示概念:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <aop:config>
  <aop:aspect id="log" ref="logging">
   <aop:pointcut id="selectAll"
   expression="execution(* com.yiibai.Student.getName(..))"/>
   <aop:before pointcut-ref="selectAll" method="beforeAdvice"/>
   <aop:after pointcut-ref="selectAll" method="afterAdvice"/>
  </aop:aspect>
  </aop:config>

  <!-- Definition for student bean -->
  <bean id="student" class="com.yiibai.Student">
   <property name="name" value="Zara" />
   <property name="age" value="11"/>
  </bean>

  <!-- Definition for logging aspect -->
  <bean id="logging" class="com.yiibai.Logging"/> 

</beans>

如果执行这些配置更改的示例应用程序,这将打印以下信息:

Going to setup student profile.
Name : Zara
Student profile has been setup.
Age : 11
Exception raised
.....
other exception content

基于@AspectJ的AOP
@ AspectJ是指声明方面的风格注释的使用Java 5注释普通的Java类。对@ AspectJ支持由包括您基于XML Schema的配置文件里面的下列元素启用。

<aop:aspectj-autoproxy/>

您还需要在以下应用程序的类路径中的AspectJ库。这些库可以在AspectJ的安装的'lib'目录,可以从网上下载他们.

  • aspectjrt.jar
  • aspectjweaver.jar
  • aspectj.jar

声明一个切面
方面类是像任何其他普通的bean,并可能有方法和字段,就像任何其他类,但他们将被标注了@Aspect 如下:

package org.xyz;

import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AspectModule {

}

他们将在XML中进行配置像任何其他的bean,如下所示:

<bean id="myAspect" class="org.xyz.AspectModule">
  <!-- configure properties of aspect here as normal -->
</bean>

声明一个切入点
一个切入点有助于确定与不同意见要执行的连接点的权益(即方法)。同时用@AspectJ的基础配置工作,切入点声明有两个部分:

切入点表达式,决定哪些方法执行我们感兴趣

一个切入点签名的包含名字和任意数量的参数。该方法的实际主体是不相关的,实际上应为空。

下面的示例定义一个名为'businessService“切入点将匹配每个方法的可用包com.xyz.myapp.service下执行中的类:

import org.aspectj.lang.annotation.Pointcut;

@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression
private void businessService() {} // signature

下面的示例定义一个名为'getName'切入点将匹配可用的软件包com.yiibai下执行getName()方法在Student类:

import org.aspectj.lang.annotation.Pointcut;

@Pointcut("execution(* com.yiibai.Student.getName(..))")
private void getname() {}

声明建议
可以声明任何使用 @{ADVICE-NAME} 注释下面给出的五个建议。这假定已经定义了一个切入点签名的方法的businessService():

@Before("businessService()")
public void doBeforeTask(){
 ...
}

@After("businessService()")
public void doAfterTask(){
 ...
}

@AfterReturning(pointcut = "businessService()", returning="retVal")
public void doAfterReturnningTask(Object retVal){
 // you can intercept retVal here.
 ...
}

@AfterThrowing(pointcut = "businessService()", throwing="ex")
public void doAfterThrowingTask(Exception ex){
 // you can intercept thrown exception here.
 ...
}

@Around("businessService()")
public void doAroundTask(){
 ...
}

可以定义内置切入点的任何意见的。下面是一个例子定义内联的切入点之前的建议:

@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
 ...
}
@AspectJ 基于AOP例子
要理解上述关系到@AspectJ的AOP的基础概念提到,让我们写这将实现几个建议的一个例子。

这里是Logging.java文件的内容。这实际上是方面模块的一个示例,它定义的方法被调用的各个点。

package com.yiibai;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;

@Aspect
public class Logging {

  /** Following is the definition for a pointcut to select
  * all the methods available. So advice will be called
  * for all the methods.
  */
  @Pointcut("execution(* com.yiibai.*.*(..))")
  private void selectAll(){}

  /**
  * This is the method which I would like to execute
  * before a selected method execution.
  */
  @Before("selectAll()")
  public void beforeAdvice(){
   System.out.println("Going to setup student profile.");
  }

  /**
  * This is the method which I would like to execute
  * after a selected method execution.
  */
  @After("selectAll()")
  public void afterAdvice(){
   System.out.println("Student profile has been setup.");
  }

  /**
  * This is the method which I would like to execute
  * when any method returns.
  */
  @AfterReturning(pointcut = "selectAll()", returning="retVal")
  public void afterReturningAdvice(Object retVal){
   System.out.println("Returning:" + retVal.toString() );
  }

  /**
  * This is the method which I would like to execute
  * if there is an exception raised by any method.
  */
  @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
  public void AfterThrowingAdvice(IllegalArgumentException ex){
   System.out.println("There has been an exception: " + ex.toString());
  }

}

以下是Student.java文件的内容:

package com.yiibai;

public class Student {
  private Integer age;
  private String name;

  public void setAge(Integer age) {
   this.age = age;
  }
  public Integer getAge() {
  System.out.println("Age : " + age );
   return age;
  }

  public void setName(String name) {
   this.name = name;
  }
  public String getName() {
   System.out.println("Name : " + name );
   return name;
  }
  public void printThrowException(){
   System.out.println("Exception raised");
   throw new IllegalArgumentException();
  }
}

以下是MainApp.java文件的内容:

package com.yiibai;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
  public static void main(String[] args) {
   ApplicationContext context =
       new ClassPathXmlApplicationContext("Beans.xml");

   Student student = (Student) context.getBean("student");

   student.getName();
   student.getAge();

   student.printThrowException();
  }
}

以下是配置文件beans.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

  <aop:aspectj-autoproxy/>

  <!-- Definition for student bean -->
  <bean id="student" class="com.yiibai.Student">
   <property name="name" value="Zara" />
   <property name="age" value="11"/>
  </bean>

  <!-- Definition for logging aspect -->
  <bean id="logging" class="com.yiibai.Logging"/> 

</beans>

创建源程序和bean配置文件完成后,让我们运行应用程序。如果一切顺利,这将打印以下信息:

Going to setup student profile.
Name : Zara
Student profile has been setup.
Returning:Zara
Going to setup student profile.
Age : 11
Student profile has been setup.
Returning:11
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
.....
other exception content

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索java
, spring
aop
spring aop 示例、spring aop编程、spring aop切面编程、spring aop类似的框架、spring框架aop,以便于您获取更多的相关知识。

时间: 2024-09-17 04:49:12

Java的Spring框架下的AOP编程模式示例_java的相关文章

详解Java的Spring框架下bean的自动装载方式_java

Spring容器可以自动装配相互协作bean之间的关系,这有助于减少对XML配置,而无需编写一个大的基于Spring应用程序的较多的<constructor-arg>和<property>元素. 自动装配模式:有下列自动装配模式,可用于指示Spring容器使用自动装配依赖注入.使用<bean/>元素的autowire属性为一个bean定义中指定自动装配模式. byName模式这种模式规定由自动装配属性名称.Spring容器在外观上自动线属性设置为byName的XML配置

基于Java的Spring框架来操作FreeMarker模板的示例_java

1.通过String来创建模版对象,并执行插值处理  import freemarker.template.Template; import java.io.OutputStreamWriter; import java.io.StringReader; import java.util.HashMap; import java.util.Map; /** * Freemarker最简单的例子 * * @author leizhimin 11-11-17 上午10:32 */ public cl

实例讲解Java的Spring框架中的AOP实现_java

简介面向切面编程(AOP)提供另外一种角度来思考程序结构,通过这种方式弥补了面向对象编程(OOP)的不足. 除了类(classes)以外,AOP提供了 切面.切面对关注点进行模块化,例如横切多个类型和对象的事务管理. (这些关注点术语通常称作 横切(crosscutting) 关注点.) Spring的一个关键的组件就是 AOP框架. 尽管如此,Spring IoC容器并不依赖于AOP,这意味着你可以自由选择是否使用AOP,AOP提供强大的中间件解决方案,这使得Spring IoC容器更加完善.

在Java的Struts框架下进行web编程的入门教程_java

当点击一个超链接或提交一个HTML表单在Struts2 的 Web应用程序,输入所收集被发送到一个Java类称为操作控制器.当动作执行后,结果选择了一个资源来呈现响应.资源通常是一个JSP,但它也可以是一个PDF文件,Excel电子表格,或一个Java applet 窗口. 假设已经建立开发环境.现在让我们继续为第一个 "Hello World" 的 struts2 项目构建.这个项目的目的是建立一个Web应用程序,它收集用户的姓名,并显示"Hello World"

浅析Java的Spring框架中IOC容器容器的应用_java

Spring容器是Spring框架的核心.容器将创建对象,它们连接在一起,配置它们,并从创建到销毁管理他们的整个生命周期.在Spring容器使用依赖注入(DI)来管理组成应用程序的组件.这些对象被称为Spring Beans. 容器获得其上的哪些对象进行实例化,配置和组装通过阅读提供的配置元数据的说明.配置元数据可以通过XML,Java注释或Java代码来表示.下面的图是Spring如何工作的高层次图. Spring IoC容器是利用Java的POJO类和配置元数据的产生完全配置和可执行的系统或

Java的MyBatis框架项目搭建与hellow world示例_java

新建项目(我使用的是maven项目)mybatis-study-01 一.加入mybatis与mysql-connector依赖包到pom文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.

举例讲解Java的Spring框架中AOP程序设计方式的使用_java

1.什么是AOP AOP是Aspect Oriented Programming的缩写,意思是面向方面编程,AOP实际是GoF设计模式的延续. 2.关于Spring AOP的一些术语: A.切面(Aspect):在Spring AOP中,切面可以使用通用类或者在普通类中以@Aspect 注解(@AspectJ风格)来实现 B.连接点(Joinpoint):在Spring AOP中一个连接点代表一个方法的执行 C.通知(Advice):在切面的某个特定的连接点(Joinpoint)上执行的动作.通

Java的Spring框架中AOP项目的一般配置和部署教程_java

0.关于AOP面向切面编程(也叫面向方面编程):Aspect Oriented Programming(AOP),是软件开发中的一个热点,也是Spring框架中的一个重要内容.利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率. AOP是OOP的延续. 主要的功能是:日志记录,性能统计,安全控制,事务处理,异常处理等等. 主要的意图是:将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对

Spring Framework中的AOP编程之入门篇

编程 作为这个介绍Spring框架中的面向方面编程(Aspect-Oriented Programming,AOP)的系列的第一部分,本文介绍了使您可以使用Spring中的面向方面特性进行快速开发的基础知识.使用跟踪和记录方面(面向方面领域的HelloWorld)作为例子,本文展示了如何使用Spring框架所独有的特性来声明切入点和通知以便应用方面.本系列的第二部分将更深入地介绍如何运用Spring中的所有通知类型和切入点来实现更实用的方面和面向方面设计模式. 本文的目的不是要介绍构成模块化J2