(十六)Spring框架——AOP

Spring框架的有一个重要组件是面向切面编程(AOP)框架。面向切面编程需要打破程序的逻辑来到一个称为关注点的的独立的部分。这个功能可以跨越程序的多个点,这些点被称为横切关注点,而且这些横切关注点是与应用的业务逻辑无关的。有很多出色的面向切面编程的例子,如日志、审计、声明性事务、安全、和缓存等。
在OOP中关键的模块单元是class(类),而在AOP中关键的模块单元是aspect(面)。依赖注入帮助我们解耦应用中相互关联的对象,而AOP帮助我们解耦互相影响的对象之间的横切关注点。AOP与编程语言中的触发器(trigger)很相似。
Spring AOP模块提供了拦截应用的拦截器,例如,我们可以在某个方法被执行之前或之后来添加额外的功能。

与AOP相关的术语:
以下术语只跟AOP相关,跟Spring没有直接的关系。
Aspect(切面):
Join point(连接点):应用程序中需要引入aop的点,简单说就是某个业务逻辑类中的方法。
Advice(通知):程序在运行到某个连接点的时候需要执行的代码,通知分五种(前置通知,后置通知,返回值通知,抛出异常通知,环绕通知)具体看下面。
Pointcut(切入点):一系列连接点的集合,所以切入点可以是一个具体类的某一指定方法,也可以是每一个包路径下的所有类中具有相同描述的一系列方法的集合。
Introduction():
Target object():
Weaving():

Advice类型:
before:切入点方法执行之前执行的方法。
after:切入点方法执行之后(无论是否正确返回)执行的方法。
after-returning:切入点方法正确执行并返回之后的执行的方法。
after-throwing:切入点方法执行抛出异常之后执行的方法。
around:切入点方法执行之前和之后都会执行的方法。

个性化的Aspects实现:
Spring支持两种实现个性化切面的方式:@AspectJ注解风格的和schema-based的方式:
基于XML格式的:
如果要使用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>

除此之外还需要导入相关依赖的jar包:aspectjrt.jar  aspectjweaver.jar  aspectj.jar  aopalliance.jar。

这里以本人亲测成功的相关jar包为准(pom.xml中添加如下依赖):

<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>

手动导入jar包目录:

spring-aop-4.3.8.RELEASE.jar
spring-beans-4.3.8.RELEASE.jar
spring-core-4.3.8.RELEASE.jar
commoms-logging-1.2.jar
spring-aspects-4.3.8.RELEASE.jar
aspectjweaver-1.8.9.jar
spring-context-4.3.8.RELEASE.jar
spring-expression-4.3.8.RELEASE.jar

声明一个aspect:
需要使用<aop:aspect>标签来声明aspect,然后使用ref属性来引用相关的bean,例子:
<aop:config>
   <aop:aspect id="myAspect" ref="aBean">
   ...
   </aop:aspect>
</aop:config>

<!--通知定义在这个bean里面-->
<bean id="aBean" class="...">
...
</bean>
声明一个pointcut:
切入点有助于确定连接点(方法)执行不同的消息。基于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>
声明advices
可以在<aop:aspect>中使用<aop:{ADVICE NAME}>声明五个消息中的任意一个或多个:
<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>

可以使用相同的或不用的方法来处理这些advices。这些方法会作为aspect模块的一部分被定义。下面提供一个配置文件的例子:

<?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 expression="execution(* com.tutorialspoint.*.*(..))" id="selectAll"/>
   		<aop:before method="beforeAdvice" pointcut-ref="selectAll"/>
   		
   		<aop:after method="afterAdvice" pointcut-ref="selectAll"/>
   		
   		<aop:after-returning method="afterReturningAdvice" returning="retVal" pointcut-ref="selectAll"/>
   		
   		<aop:after-throwing method="afterThrowingAdvice" pointcut-ref="selectAll" throwing="ex"/>
   		
   	</aop:aspect>
   </aop:config>
   
   <bean id="student" class="com.tutorialspoint.Student">
   	<property name="name" value="Zara"/>
   	<property name="age" value="11"></property>
   </bean>
   
   <bean id="logging" class="com.tutorialspoint.Logging"></bean>
</beans>
相关类文件:

package com.tutorialspoint;

public class Logging {
	/**
	 * This is the mothed which i would like 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.
	 * @param 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.
	 * @param ex
	 */
	public void afterThrowingAdvice(IllegalArgumentException ex){
		System.out.println("There has been an exception:" + ex.toString());
	}
}

package com.tutorialspoint;

public class Student {
	
	private Integer age;
	private String name;
	
	public Integer getAge() {
		System.out.println("Age:" + age);
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getName() {
		System.out.println("Name:" + name);
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public void printThrowException(){
		System.out.println("Exception raised");
		throw new IllegalArgumentException();
	}

}

package com.tutorialspoint;

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

public class MainApp {
	
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml");
		
		Student student = (Student)context.getBean("student");
		
		//student.getName();
		student.getAge();
		//student.printThrowException();
	}

}


基于@AspectJ的:

如果想实现@AspectJ支持,必须在配置文件中加入以下标签:

<aop:aspectj-autoproxy/>
依赖的jar包完全参考上面基于xml的例子。

声明一个aspect:

切面类与一般的类的唯一区别是引入了@Aspect注解

package org.xyz;

import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AspectModule {
}
接下来还需要在配置文件中配置切面类的bean

<bean id = "myAspect" class = "org.xyz.AspectModule">
   <!-- configure properties of aspect here as normal -->
</bean>
声明切入点(pointcut):使用注解配置切入点需要两个部分:

point expression:精确的决定连接点

point signature:由名称和参数构成的方法

示例1:定义匹配指定包下面的所有方法的切入点

import org.aspectj.lang.annotation.Pointcut;

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

示例2:定义匹配一个指定方法的切入点

import org.aspectj.lang.annotation.Pointcut;

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

声明advices:假设已经声明了一个切入点签名方法businessServices()

@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(){
   ...
}

也可以为每一个advices定义内联切入点:

@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
   ...
}

下面提供一个具体的实例:

配置文件:

<?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></aop:aspectj-autoproxy>
   
   <bean id = "student" class = "com.tutorialspoint.Student">
   	<property name="name">
   		<value>Zara</value>
   	</property>
   	<property name="age">
   		<value>11</value>
   	</property>
   </bean>
   
   <bean id = "logging" class = "com.tutorialspoint.Logging"></bean>
   
   
</beans>

Logging类:定义切面

package com.tutorialspoint;

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

@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.tutorialspoint.*.*(..))")
    private void selectAll(){}
    
    /**
     * This is the method which i would like to execute before a
     * selected method execution.
     */
    @Before(value ="execution(* com.tutorialspoint.Student.getName(..))")
    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.
     * @param retVal
     */
    @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 an method.
     * @param ex
     */
    @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
    public void afterThrowingAdvice(IllegalArgumentException ex){
        System.out.println("There has been an exception:" + ex.toString());
    }
}

Student类:业务逻辑类

package com.tutorialspoint;

public class Student {
	
	private Integer age;
	private String name;
	public Integer getAge() {
		System.out.println("Age:" + age);
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getName() {
		System.out.println("Name:" + name);
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public void printThrowException(){
		System.out.println("Exception raised");
		throw new IllegalArgumentException();
	}

}

MainApp测试类:

package com.tutorialspoint;

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

public class MainApp {
	
	public static void main(String[] args) {
		
		ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
		
		Student student = (Student) context.getBean("student");
		
		student.getName();
		student.getAge();
		
		student.printThrowException();
	}
	
}

来源:https://www.tutorialspoint.com/spring/aop_with_spring.htm

参考:http://blog.youkuaiyun.com/moreevan/article/details/11977115


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值