Spring学习之08AOP使用

AOP

aop介绍

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

AOP 即 Aspect Oriented Program 面向切面编程

  • 所谓的核心业务,比如登陆,增加数据,删除数据都叫核心业务
  • 所谓的周边功能,比如性能统计,日志,事务管理等等

周边功能在 Spring 的面向切面编程AOP思想里,即被定义为切面

在面向切面编程AOP的思想里面,核心业务功能和切面功能分别独立进行开发,然后把切面功能和核心业务功能 “编织” 在一起,这就叫AOP

aop概念

  • 切入点(Pointcut)
    在哪些类,哪些方法上切入(where

  • 通知(Advice)
    在方法执行的什么实际(**when:**方法前/方法后/方法前后)做什么(**what:**增强的功能)

  • 切面(Aspect)
    切面 = 切入点 + 通知,通俗点就是:在什么时机,什么地方,做什么增强!

  • 织入(Weaving)
    把切面加入到对象,并创建出代理对象的过程。(由 Spring 来完成)

在这里插入图片描述

在这里插入图片描述

Spring在运行时通知对象

通过在代理类中包裹切面,Spring在运行期把切面织入到Spring管理的bean中。代理封装了目标类,并拦截被通知方法的调用,再把调用转发给真正的目标bean。当代理拦截到方法调用时,在调用目标bean方法之前,会执行切面逻辑。

直到应用需要被代理的bean时,Spring才创建代理对象。如果使用的是ApplicationContext的话,在ApplicationContext从BeanFactory中加载所有bean的时候,Spring才会创建被代理的对象。因为Spring运行时才创建代理对象,所以我们不需要特殊的编译器来织入SpringAOP的切面g

通过切点来选择连接点

在Spring AOP中,要使用AspectJ的切点表达式语言来定义切点。

由于Sring是基于代理的,而某些切点表达式是与基于代理的AOP无关的。下表列出了Spring AOP所支持的AspectJ切点指示器。

AspectJ指示器描述
arg()限制连接点匹配参数为指定类型的执行方法
@args()限制连接点匹配参数有指定注解标注的执行方法
execution()用于匹配是连接点的执行方法
this()限制连接点匹配AOP代理的bean引用为指定类型的类
target限制连接点匹配目标对象为指定类型的类
@target()限制连接点匹配特定的执行对象,这些对象对应的类要具有指定类型的注解
within()限制连接点匹配指定的类型
@within()限制连接点匹配指定注解所标注的类型(当使用Spring AOP时,方法定义在由指定的注解所标注的类里)
@annotation限制匹配带有指定注解的连接点

在Spring中尝试使用AspectJ其他指示器时,将会抛出IllegalArgument-Exception异常。

注意:当我们查看如上所展示的这些Spring支持的指示器时,只有execution指示器是实际执行匹配的,而其他的指示器都是用来限制匹配的。

package concert;

public interface Performance {
     public void perform() ;
}

假设我们想编写Performance的perform()方法触发的通知,下面展示了切点表达式的写法

在这里插入图片描述

使用AspectJ切点表达式来选择Performance的perform()方法

现在假设我们需要配置的切点仅匹配concert包。我们可以使用within()指示器来限制匹配,如下图

在这里插入图片描述

使用within指示器限制切点范围

注意:我们使用了“&&”操作符把execution()和within()指示器连接在一起形成与(可以用and代替)关系(切点必须匹配所有的指示器)。类似地,我们可以使用“||操作符”来标识或(可以用or代替)关系,而使用“!”操作符来标识非(可以用not代替)操作

在切点中选择bean

除了表所列的指示器外,Spring还引入了一个新的bean()指示器,它允许我们在切点表达式中使用bean的ID来标识bean。bean()使用beanID或bean名称作为参数限制切点只匹配特定的bean。

例如,考虑如下的切点:

execution(* concert.Performance.perform()) 
            and bean('woodstock')
12

还可以使用非操作为除了特定ID以外的其他bean应用通知:

execution(* concert.Performance.perform()) 
            and !bean('woodstock')

使用注解创建切面

我们已经定义了Performance接口,它是切面中切点的目标对象。现在,让我们使用AspectJ注解来定义切面

AspectJ提供了五个注解来定义通知,如下表所示。

注  解通  知
@After通知方法会在目标方法返回或抛出异常后调用
@AfterReturning通知方法会在目标方法返回后调用
@AfterThrowing通知方法会在目标方法抛出异常后调用
@Around通知方法会将目标方法封装起来
@Before通知方法会在目标方法调用之前执行

定义切面

我们将观众定义为一个切面,并将其应用到演出上就是较为明智的做法。
下面为Audience类的代码

package com.springinaction.perf;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

//切面 POJO
@Aspect
public class Audience {

    //定义命名的切点
    @Pointcut("execution(** com.springinaction.perf.Performance.perform(..))")
    public void performance(){
    }

    //定义通知
    @Before("performance()")   // 表演之前
    public void silenceCellPhones(){
        System.out.println("Silencing cell phones");
    }

    @Before("performance()") // 表演之前
    public void takeSeats(){
        System.out.println("Taking seats");
    }

    @AfterReturning("performance()")  // 表演之后
    public void applause(){
        System.out.println("CLAP CLAP CLAP");
    }

    @AfterThrowing("performance()")   // 表演失败之后
    public void demandRefund(){
        System.out.println("Demanding a refund");
    }

    @Around("performance()")  // 环绕通知方法
    public void watchPerformance(ProceedingJoinPoint jp){
        try {
            System.out.println("Silencing cell phones Again");
            System.out.println("Taking seats Again");
            jp.proceed();
            System.out.println("CLAP CLAP CLAP Again");
        }
        catch (Throwable e){
            System.out.println("Demanding a refund Again");
        }
    }

}

关于环绕通知,我们首先注意到它接受ProceedingJoinPoint作为参数。这个对象是必须要有的,因为要在通知中通过它来调用被通知的方法。

需要注意的是,一般情况下,别忘记调用proceed()方法。如果不调用,那么通知实际上会阻塞对被通知方法的调用,也许这是所期望的效果。当然,也可以多次调用,比如要实现一个场景是实现重试逻辑。

除了注解和没有实际操作的performance()方法,Audience类依然是一个POJO,可以装配为Spring中的bean


注意,注解中直接引用了定义命名的切点的方法,实际上这是一种优化,也可以在通知注解中直接使用切点表达式也是行得通的,但是这种方式在切点被引用多次的时候过于冗杂,会使得代码量增加


除了注解和没有实际操作的performance()方法,Audience类依然是一个POJO,可以装配为Spring中的bean

@Bean
public Audience audience(){   // 声明Audience
    return new Audience();
}

除了定义切面外,还需要启动自动代理,才能使这些注解解析。
如果使用JavaConfig的话,需要如下配置

package com.springinaction.perf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan
@EnableAspectJAutoProxy   //启动AspectJ自动代理
public class AppConfig {

    @Bean
    public Audience audience(){   // 声明Audience
        return new Audience();
    }
}

假如在Spring中要使用XML来装配bean的话,那么需要使用Spring aop命名空间中的<aop:aspectj-autoproxy>元素。

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.springinaction.perf" />
    <aop:aspectj-autoproxy />
    <bean id="audience" class="com.springinaction.perf.Audience" />
</beans>

无论使用JavaConfig还是XML,Aspect自动代理都会使用@Aspect注解的bean创建一个代理,这个代理会围绕着所有该切面的切点所匹配的bean。这种情况下,将会为Concert的bean创建一个代理,Audience类中的通知方法将会在perform()调用前后执行。

我们需要记住的是,Spring的AspectJ自动代理仅仅使用@AspectJ作为创建切面的指导,切面依然是基于代理的。本质上,它依然是Spring基于代理的切面。

处理通知中的参数

目前为止,除了环绕通知,其他通知都没有参数。如果切面所通知的方法确实有参数该怎么办呢?切面能访问和使用传递给被通知方法的参数吗?

为了阐述这个问题,我们来看一下BlankDisc样例。假设你想记录每个磁道被播放的次数。为了记录次数,我们创建了TrackCounter类,它是通知playTrack()方法的一个切面。

package com.springinaction.disc;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import java.util.HashMap;
import java.util.Map;

@Aspect
public class TrackCounter {

    private Map<Integer, Integer> trackCounts = new HashMap<>();

    @Pointcut("execution(* com.springinaction.disc.CompactDisc.playTrack(int))" +
     "&& args(trackNumber)")  // 通知playTrack()方法
    public void trackPlayed(int trackNumber){}

    @Before("trackPlayed(trackNumber)")  // 在播放前,为该磁道计数
    public void countTrack(int trackNumber){
        int currentCount = getPlayCount(trackNumber);
        trackCounts.put(trackNumber, currentCount + 1);
    }

    public int getPlayCount(int trackNumber){
        return trackCounts.containsKey(trackNumber) ? trackCounts.get(trackNumber) : 0;
    }
}

以下为切点表达式分解

在这里插入图片描述

在切点表达式中声明参数,这个参数传入到通知方法中

其中args(trackNumber)限定符表明传递给playTrack()方法的int类型参数也会传递到通知中去。trackNumber也与切点方法签名中的参数相匹配。切点定义中的参数与切点方法中的参数名称是一样的。

其中args(trackNumber)限定符表明传递给playTrack()方法的int类型参数也会传递到通知中去。trackNumber也与切点方法签名中的参数相匹配。切点定义中的参数与切点方法中的参数名称是一样的。

启动AspectJ自动代理以及定义bean

package com.springinaction.disc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableAspectJAutoProxy
public class TrackCounterConfig {

    @Bean
    public CompactDisc sgtPeppers(){
        BlankDisc cd = new BlankDisc();
        cd.setTitle("Sgt. Pepper's Lonely Hearts Club Band");
        cd.setArtist("The Beatles");
        List<String> tracks = new ArrayList<>();
        tracks.add("Sgt. Pepper's Lonely Hearts Club Band");
        tracks.add("With a Little Help from My Friends");
        tracks.add("Luck in the Sky with Diamonds");
        tracks.add("Getting Better");
        tracks.add("Fixing a Hole");
        tracks.add("Feel My Heart");
        tracks.add("L O V E");
        cd.setTracks(tracks);
        return cd;
    }

    @Bean
    public TrackCounter trackCounter(){
        return new TrackCounter();
    }

}

最后的简单测试

package com.springinaction;

import static org.junit.Assert.*;
import com.springinaction.disc.CompactDisc;
import com.springinaction.disc.TrackCounter;
import com.springinaction.disc.TrackCounterConfig;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TrackCounterConfig.class)
public class TrackCounterTest {

    @Rule
    public final StandardOutputStreamLog log = new StandardOutputStreamLog();

    @Autowired
    private CompactDisc cd;

    @Autowired
    private TrackCounter counter;

    @Test
    public void testTrackCounter(){
        cd.playTrack(1);
        cd.playTrack(2);
        cd.playTrack(3);
        cd.playTrack(3);
        cd.playTrack(3);
        cd.playTrack(3);
        cd.playTrack(7);
        cd.playTrack(7);

        assertEquals(1,counter.getPlayCount(1));
        assertEquals(1,counter.getPlayCount(2));
        assertEquals(4,counter.getPlayCount(3));
        assertEquals(0,counter.getPlayCount(4));
        assertEquals(0,counter.getPlayCount(5));
        assertEquals(0,counter.getPlayCount(6));
        assertEquals(2,counter.getPlayCount(7));
    }
}

通过注解引入新功能

我们除了给已有的方法添加新功能外,还可以添加一些额外的功能。

回顾一下,在Spring中,切面只是实现了它们所包装bean相同的接口代理。如果除了实现这些接口,代理也能暴露新接口。即便底层实现类并没有实现这些接口,切面所通知的bean也能实现新的接口。下图展示了它们是如何工作的。

在这里插入图片描述

使用Spring AOP,我们可以为bean引入新的方法。代理拦截调用并委托给实现该方法的其他对象

需要注意的是,当引入接口的方法被调用时,代理会把此调用委托给实现了新接口的某个其他对象。实际上,一个bean的实现被拆分到了多个类中。

为了验证能行得通,我们为所有的Performance实现引入Encoreable接口

package com.springinaction.perf;

public interface Encoreable {
    void performEncore();
}
12345

借助于AOP,我们创建一个新的切面

package com.springinaction.perf;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;

@Aspect
public class EncoreableIntroducer {   // 需要给Performance和其实现类额外添加方法的实现
    @DeclareParents(value = "com.springinaction.perf.Performance+",
                    defaultImpl = DefaultEncoreable.class)
    public static Encoreable encoreable;

其中@DeclareParents注解,将Encoreable接口引入到Performance bean中。
@DeclareParents注解有三个部门组成:

  • value属性指定了哪种类型的bean要引入该接口。(本例中,就是Performance,加号表示Performance的所有子类型)
  • defaultImpl属性指定了为引入功能提供实现的类。
  • @DeclareParents注解所标注的静态属性指明了要引入的接口。

然后需要在配置中声明EncoreableIntroducer的bean

@Bean
public EncoreableIntroducer encoreableIntroducer(){
    return new EncoreableIntroducer();
}
1234

当调用委托给被代理的bean或被引入的实现,取决于调用的方法属性被代理的bean还是属性被引入的接口。

在Spring中,注解和自动代理提供了一种很便利的方式来创建切面。但有一个劣势:必须能够为通知类添加注解,要有源码。

如果没有源码或者不想注解到你的代码中,能可选择Spring XML配置文件中声明切面。

在XML中声明切面

如果声明切面,但不能为通知类添加注解时,需要转向XML配置了。

在Spring的aop命名空间中,提供了多个元素用来在XML中声明切面,如下表所示

AOP配置元素用途
<aop:advisor>定义AOP通知器
<aop:after>定义AOP后置通知(不管被通知的方法是否执行成功)
<aop:after-returning>定义AOP返回通知
<aop:after-throwing>定义AOP异常通知
<aop:around>定义AOP环绕通知
<aop:aspect>定义一个切面
<aop:aspectj-autoproxy>启用@AspectJ注解驱动的切面
<aop:before>定义AOP前置通知
<aop:config>顶层的AOP配置元素。大多数的<aop:*>元素必须包含在<aop:config>元素内
<aop:declare-parents>以透明的方式为被通知的对象引入额外的接口
<aop:pointcut>定义一个切点

我们重新看一下Audience类,这一次我们将它所有的AspectJ注解全部移除掉:

package com.springinaction.perf;

public class Audience {

    public void silenceCellPhones(){
        System.out.println("Silencing cell phones");
    }

    public void takeSeats(){
        System.out.println("Taking seats");
    }

    public void applause(){
        System.out.println("CLAP CLAP CLAP");
    }

    public void demandRefund(){
        System.out.println("Demanding a refund");
    }

    public void watchPerformance(ProceedingJoinPoint jp){
        try {
            System.out.println("Silencing cell phones Again");
            System.out.println("Taking seats Again");
            jp.proceed();
            System.out.println("CLAP CLAP CLAP Again");
        }
        catch (Throwable e){
            System.out.println("Demanding a refund Again");
        }
    }
}

声明前置、后置以及环绕通知

下面展示了所需要的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/aop
       http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="audience" class="com.springinaction.perf.Audience" />
    <bean id="performance" class="com.springinaction.perf.Concert"/>

    <aop:config>
        <aop:aspect ref="audience">
            <aop:pointcut id="perf" expression="execution(* com.springinaction.perf.Performance.perform(..))" />
            <aop:before pointcut-ref="perf" method="silenceCellPhones" />
            <aop:before pointcut-ref="perf" method="takeSeats" />
            <aop:after-returning pointcut-ref="perf" method="applause" />
            <aop:after-throwing pointcut-ref="perf" method="demandRefund"/>
            <aop:around pointcut-ref="perf" method="watchPerformance"/>
        </aop:aspect>
    </aop:config>

</beans>

为通知传递参数

我们使用XML来配置BlankDisc。
首先,移除掉TrackCounter上所有的@AspectJ注解。

package com.springinaction.disc;
import java.util.HashMap;
import java.util.Map;

public class TrackCounter {

    private Map<Integer, Integer> trackCounts = new HashMap<>();

    // 在播放前,为该磁道计数
    public void countTrack(int trackNumber){
        int currentCount = getPlayCount(trackNumber);
        trackCounts.put(trackNumber, currentCount + 1);
    }

    public int getPlayCount(int trackNumber){
        return trackCounts.containsKey(trackNumber) ? trackCounts.get(trackNumber) : 0;
    }
}

下面展示了在XML中将TrackCounter配置为参数化的切面

<?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/aop
       http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="trackCounter" class="com.springinaction.disc.TrackCounter" />

    <bean id="cd" class="com.springinaction.disc.BlankDisc" >
        <property name="title" value="Sgt. Pepper's Lonely Hearts Club Band" />
        <property name="artist" value="The Beatles" />
        <property name="tracks">
            <list>
                <value>Sgt. Pepper's Lonely Hearts Club Band</value>
                <value>With a Little Help from My Friends</value>
                <value>Lucy in the Sky with Diamonds</value>
                <value>Getting Better</value>
                <value>Fixing a Hole</value>
                <value>Feel My Heart</value>
                <value>L O V E</value>
            </list>
        </property>
    </bean>

    <aop:config>
        <aop:aspect ref="trackCounter">
            <aop:pointcut id="trackPlayed" expression="
            execution(* com.springinaction.disc.CompactDisc.playTrack(int))
            and args(trackNumber)" />

            <aop:before pointcut-ref="trackPlayed" method="countTrack"/>
        </aop:aspect>
    </aop:config>


</beans>

注意:在XML中,“&”符号会被解析为实体的开始,所用“and”关键字。

通过切面引入新的功能

使用Spring aop命名空间中的<aop:declare-parents>元素,我们可以实现相同的功能。

<aop:aspect>
      <aop:declare-parents types-matching="com.springinaction.perf.Performance+"
                                 implement-interface="com.springinaction.perf.Encoreable"
                                 default-impl="com.springinaction.perf.DefaultEncoreable" />
</aop:aspect>

我们还可以使用delegate-ref属性来标识

<aop:aspect>
    <aop:declare-parents types-matching="com.springinaction.perf.Performance+"
                         implement-interface="com.springinaction.perf.Encoreable"
                         delegate-ref="defaultEncoreable" />
</aop:aspect>

delegate-ref属性引用了一个Spring bean作为引入的委托。

<bean id="defaultEncoreable" class="com.springinaction.perf.DefaultEncoreable" /

注入AspectJ切面

AspectJ提供了Spring AOP所不能支持的许多类型的切点。例如:构造器切点就非常方便。

为了演示,我们新创建一个切面,我们以切面的方式创建一个评论员的角色,演出后提一些批评意见。
首先创建这样的一个切面

package com.springinaction.perf;

public aspect CriticAspect {
    public  CriticAspect(){}

    pointcut performance() : execution(* perform(..));

    after() returning : performance() {
       System.out.println(criticismEngine.getCriticism());
    }

    private CriticismEngine criticismEngine;

    public CriticismEngine getCriticismEngine() {
        return criticismEngine;
    }

    public void setCriticismEngine(CriticismEngine criticismEngine) {
        this.criticismEngine = criticismEngine;
    }
}

然后是CriticismEngine的接口

package com.springinaction.perf;

public interface CriticismEngine {
    String getCriticism();
}
12345

CriticismEngine的实现类

package com.springinaction.perf;

public class CriticismEngineImpl implements CriticismEngine {

    public CriticismEngineImpl(){}

    @Override
    public String getCriticism() {
        int i = (int) (Math.random() * criticismPool.length);
        return criticismPool[i];
    }

    private String[] criticismPool;
    public void setCriticismPool(String[] criticismPool){
        this.criticismPool = criticismPool;
    }
}

为CriticismEngineImpl注入list

<bean id="criticismEngine" class="com.springinaction.perf.CriticismEngineImpl">
    <property name="criticismPool">
        <list>
            <value>Worst performance ever!</value>
            <value>I laughed, I cried, then I realized I was at the wrong show.</value>
            <value>A must see show!</value>
        </list>
    </property>
</bean>

在展示如何实现注入之前,我们必须清楚AspectJ切面根本不需要Spring就可以织入到我们的应用中。如果想使用Spring的依赖注入,那就需要把切面声明为一个Spring配置中的<bean>

<bean class="com.springinaction.perf.CriticAspect" factory-method="aspectOf">
    <property name="criticismEngine" ref="criticismEngine"/>
</bean>

通常情况下,Spring bean由Spring容器初始化,但是AspectJ切面AspectJ在运行期创建的。等到Spring有机会为CriticAspect注入CriticismEngine时,CriticAspect已经被实例化了。

因为Spring不能负责创建CriticAspect,那就不能在Spring中简单地把CriticAspect声明为一个bean。相反,我们需要一种方式为Spring获得已经有AspectJ创建的CriticAspect实例的句柄,从而可以注入CriticismEngine。幸好,所有AspectJ切面都提供了一个静态的aspectOf()方法,该方法返回切面的一个单例。所有为了获得切面的实例,我们必须使用factory-method来调用aspectOf()而不是调用CriticAspect的构造器方法。

简而言之,Spring不能像之前那样使用<bean>声明来创建一个CriticAspect实例-它已经在运行时有AspectJ创建完成了。Spring需要通过aspectOf()工厂方法获得切面的引用,然后像<bean>元素规定的那样在该对象上执行依赖注入。

小结

AOP是面向对象编程的一个强大补充。通过AspectJ,我们现在可以把之前分散在应用各处的行为放入可重用的模块中。我们显示地声明在何处如何应用该行为。这有效减少了代码冗余,并让我们的类关注自身的主要功能。
Spring提供了一个AOP框架,让我们把切面插入到方法执行的周围。

现在我们已经学会如何把通知织入前置、后置和环绕方法的调用中,以及为处理异常增加自定义的行为。关于在Spring应用中如何使用切面,我们可以有多种选择。通过使用@AspectJ注解和简化的配置命名空间,在Spring中装配通知和切点变得非常简单。

最后,当Spring AOP不能满足需求时,我们必须转向更为强大的AspectJ。对于这些场景,我们了解了如何使用Spring为AspectJ切面注入依赖。

此时此刻,我们已经覆盖了Spring框架的基础知识,了解到如何配置Spring容器以及如何为Spring管理的对象应用切面。正如我们所看到的,这些核心技术为创建松散耦合的应用奠定了坚实的基础。现在,我们越过这些基础的内容,看一下如何使用Spring构建真实的应用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值