基于配置的Spring AOP

简介:

前面几篇学习了Spring的依赖注入,这篇开始学习另一个核心功能——面向切面编程AOP

  通过本文,你可以了解到:

  1 Spring xml规范

  2 通过配置文件实现面向切面编程

  3 对比与传统AOP编程

Spring的xml文件

  Spring的xml一般起名叫做bean.xml或者xxxapplication.xml这种,然后放在src下通过ClassPathXmlApplicationContext进行加载。文件的内容如下:

复制代码
<?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"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> 
    
    <bean id="audience"class="com.spring.test.aop.Audience"/>

    <aop:config>
    </aop:config>
</beans>
复制代码

  最上面的是xml的编码,这个就不解释了。

  下面的<beans>是Spring的配置标签,beans里面几个重要的属性

  xmlns:

  是默认的xml文档解析格式,即spring的beans。地址是http://www.springframework.org/schema/beans。

  通过设置这个属性,所有在beans里面声明的属性,可以直接通过<>来使用,比如<bean>等等。

  xmlns:xsi:

  是xml需要遵守的规范,通过URL可以看到,是w3的统一规范,后面通过xsi:schemaLocation来定位所有的解析文件。

  xmlns:aop:

  这个是重点,是我们这里需要使用到的一些语义规范,与面向切面AOP相关。

  xmlns:tx:

  Spring中与事务相关的配置内容。

  

  一个XML文件,只能声明一个默认的语义解析的规范。

  例如上面的xml中就只有beans一个是默认的,其他的都需要通过特定的标签来使用,比如aop,它自己有很多的属性,如果要使用,前面就必须加上aop:xxx才可以。比如上面的aop:config。

  类似的,如果默认的xmlns配置的是aop相关的语义解析规范,那么在xml中就可以直接写config这种标签了。

基于配置的AOP编程过程

  首先,如果要在工程中使用AOP需要几个jar包:

  1 Aop的核心包,即org.springframework.aop-xxx.jar

  2 Spring的联盟包:aopalliance-1.0.jar

  3 aspectJ相关的jar包:aspectjrt.jar aspectjweaver.jar

  4 如果使用了动态代理,还需要添加cglib相关的jar包:cglib.zip

  首先需要一个AOP的切面类,用于定义各种响应事件

复制代码
package com.spring.test.aop;

public class Audience {
    public void takeSeats(){
        System.out.println("The audience is taking their seats.");
    }
    public void turnOffCellPhones(){
        System.out.println("The audience is turning off their cellphones");
    }
    public void applaud(){
        System.out.println("CLAP CLAP CLAP");
    }
    public void demandRefund(){
        System.out.println("Boo! We want money back");
    }
}
复制代码

  然后在bean.xml中编写aop:config的相关内容:

复制代码
...省略beans的定义内容

    <bean id="audience" class="com.spring.test.aop.Audience"/>
    
    <bean id="sax" class="com.spring.test.setter.Saxophone"/>
    <bean id="kenny" class="com.spring.test.setter.Instrumentalist">
         <property name="song" value="Jingle Bells" />
         <property name="age" value="25" />
         <property name="instrument" ref="sax"/>
    </bean>
    
    <aop:config proxy-target-class="true">
        <aop:aspect ref="audience">
            <aop:pointcut id="performance" expression="execution(* com.spring.test.action1.Performer.perform(..))"/>
            
            <aop:before pointcut-ref="performance" method="takeSeats"/>
            <aop:before pointcut-ref="performance" method="turnOffCellPhones"/>
            <aop:after-returning pointcut-ref="performance" method="applaud"/>
            <aop:after-throwing pointcut-ref="performance" method="demandRefund"/>
        </aop:aspect>
    </aop:config>
</beans>
复制代码

  这里面的aop:pointcut 就是使用AspectJ来定位的。意思是:当执行com.spring.test.action1.Performer的perform方法时,就会触发该切面的事件响应。

  而Performer以及Instrumentalist等等的代码,就在下面简单的都罗列出来了:

  配置文件bean.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"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> 
    
    <bean id="audience" class="com.spring.test.aop.Audience"/>
    
    <bean id="sax" class="com.spring.test.setter.Saxophone"/>
    <bean id="kenny" class="com.spring.test.setter.Instrumentalist">
         <property name="song" value="Jingle Bells" />
         <property name="age" value="25" />
         <property name="instrument" ref="sax"/>
    </bean>
    
    <aop:config proxy-target-class="true">
        <aop:aspect ref="audience">
            <aop:pointcut id="performance" expression="execution(* com.spring.test.action1.Performer.perform(..))"/>
            
            <aop:before pointcut-ref="performance" method="takeSeats"/>
            <aop:before pointcut-ref="performance" method="turnOffCellPhones"/>
            <aop:after-returning pointcut-ref="performance" method="applaud"/>
            <aop:after-throwing pointcut-ref="performance" method="demandRefund"/>
        </aop:aspect>
    </aop:config>
</beans>
复制代码

  表演者接口Performer.java

package com.spring.test.action1;

public interface Performer {
    void perform() throws PerformanceException;
}

  表演者实现类Instrumentalist.java

复制代码
package com.spring.test.setter;

import com.spring.test.action1.PerformanceException;
import com.spring.test.action1.Performer;

public class Instrumentalist implements Performer{
    private String song;
    private int age;
    private Instrument instrument;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSong() {
        return song;
    }
    public void setSong(String song) {
        this.song = song;
    }
    public Instrument getInstrument() {
        return instrument;
    }
    public void setInstrument(Instrument instrument) {
        this.instrument = instrument;
    }
    public Instrumentalist(){}
    public Instrumentalist(String song,int age,Instrument instrument){
        this.song = song;
        this.age = age;
        this.instrument = instrument;
    }
    public void perform() throws PerformanceException {
        System.out.println("Instrumentalist age:"+age);
        System.out.print("Playing "+song+":");
        instrument.play();
    }
}
复制代码

  内部bean接口Instrument.java

package com.spring.test.setter;

public interface Instrument {
    public void play();
}

  内部bean实现类Saxophone.java

复制代码
package com.spring.test.setter;

public class Saxophone implements Instrument {
    public Saxophone(){}
    public void play() {
        System.out.println("TOOT TOOT TOOT");
    }
}
复制代码

  测试主函数main

复制代码
package com.spring.test.setter;

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

import com.spring.test.action1.PerformanceException;

public class test {
    public static void main(String[] args) throws PerformanceException {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
        
        Instrumentalist performer = (Instrumentalist)ctx.getBean("kenny");
        performer.perform();
        
    }
}
复制代码

  运行结果:

The audience is taking their seats.
The audience is turning off their cellphones
Instrumentalist age:25
Playing Jingle Bells:TOOT TOOT TOOT
CLAP CLAP CLAP

  通过这种声明方式,可以 快速的实现切点与切面的整合,成为下面这种格式的新代码:

复制代码
class{
  try{  
  audience.takeSeats();    
  audience.turnOffCellphones();

  performance.perform();  

  audience.applaud();  
  }catch(Exception){
    audience.demandRefund();
  }   
}
复制代码

  面向切面的好处,要在实际工作中多加领会才可以,常用的场景就是日志的记录了。

与传统的AOP编程相比

  前面也做过一个传统的spring aop的实现方法:http://www.cnblogs.com/xing901022/p/4143696.html

  不得不说,通过ProxyFactoryBean达到的面向切面的编程,过于复杂,光是那几个功能就要好好理解一番。

  而基于配置的AOP使用就要简单的多,只需要一个切面的程序,然后通过配置文件就可以完全解耦的融入到切点中。

本文转自博客园xingoo的博客,原文链接:基于配置的Spring AOP,如需转载请自行联系原博主。
相关文章
|
20天前
|
XML Java 数据格式
Spring IOC—基于XML配置Bean的更多内容和细节(通俗易懂)
Spring 第二节内容补充 关于Bean配置的更多内容和细节 万字详解!
116 18
Spring IOC—基于XML配置Bean的更多内容和细节(通俗易懂)
|
7天前
|
设计模式 Java 测试技术
spring复习04,静态代理动态代理,AOP
这篇文章讲解了Java代理模式的相关知识,包括静态代理和动态代理(JDK动态代理和CGLIB),以及AOP(面向切面编程)的概念和在Spring框架中的应用。文章还提供了详细的示例代码,演示了如何使用Spring AOP进行方法增强和代理对象的创建。
spring复习04,静态代理动态代理,AOP
|
8天前
|
前端开发 Java Spring
关于spring mvc 的 addPathPatterns 拦截配置常见问题
关于spring mvc 的 addPathPatterns 拦截配置常见问题
|
21天前
|
Java 数据库连接 数据库
Spring基础3——AOP,事务管理
AOP简介、入门案例、工作流程、切入点表达式、环绕通知、通知获取参数或返回值或异常、事务管理
Spring基础3——AOP,事务管理
|
21天前
|
Java 数据库连接 Maven
Spring基础1——Spring(配置开发版),IOC和DI
spring介绍、入门案例、控制反转IOC、IOC容器、Bean、依赖注入DI
Spring基础1——Spring(配置开发版),IOC和DI
|
1月前
|
IDE Java 开发工具
还在为繁琐的配置头疼吗?一文教你如何用 Spring Boot 快速启动,让开发效率飙升,从此告别加班——打造你的首个轻量级应用!
【9月更文挑战第2天】Spring Boot 是一款基于 Spring 框架的简化开发工具包,采用“约定优于配置”的原则,帮助开发者快速创建独立的生产级应用程序。本文将指导您完成首个 Spring Boot 项目的搭建过程,包括环境配置、项目初始化、添加依赖、编写控制器及运行应用。首先需确保 JDK 版本不低于 8,并安装支持 Spring Boot 的现代 IDE,如 IntelliJ IDEA 或 Eclipse。
86 5
|
2月前
|
缓存 Java 开发者
Spring高手之路22——AOP切面类的封装与解析
本篇文章深入解析了Spring AOP的工作机制,包括Advisor和TargetSource的构建与作用。通过详尽的源码分析和实际案例,帮助开发者全面理解AOP的核心技术,提升在实际项目中的应用能力。
23 0
Spring高手之路22——AOP切面类的封装与解析
|
2月前
|
Java 微服务 Spring
Spring Cloud全解析:配置中心之解决configserver单点问题
但是如果该configserver挂掉了,那就无法获取最新的配置了,微服务就出现了configserver的单点问题,那么如何避免configserver单点呢?
|
2月前
|
Java Spring XML
掌握面向切面编程的秘密武器:Spring AOP 让你的代码优雅转身,横切关注点再也不是难题!
【8月更文挑战第31天】面向切面编程(AOP)通过切面封装横切关注点,如日志记录、事务管理等,使业务逻辑更清晰。Spring AOP提供强大工具,无需在业务代码中硬编码这些功能。本文将深入探讨Spring AOP的概念、工作原理及实际应用,展示如何通过基于注解的配置创建切面,优化代码结构并提高可维护性。通过示例说明如何定义切面类、通知方法及其应用时机,实现方法调用前后的日志记录,展示AOP在分离关注点和添加新功能方面的优势。
38 0
|
2月前
|
Java Spring 开发者
解锁 Spring Boot 自动化配置的黑科技:带你走进一键配置的高效开发新时代,再也不怕繁琐设置!
【8月更文挑战第31天】Spring Boot 的自动化配置机制极大简化了开发流程,使开发者能专注业务逻辑。通过 `@SpringBootApplication` 注解组合,特别是 `@EnableAutoConfiguration`,Spring Boot 可自动激活所需配置。例如,添加 JPA 依赖后,只需在 `application.properties` 配置数据库信息,即可自动完成 JPA 和数据源设置。这一机制基于多种条件注解(如 `@ConditionalOnClass`)实现智能配置。深入理解该机制有助于提升开发效率并更好地解决问题。
49 0
下一篇
无影云桌面