【Spring实战】—— 13 AspectJ注解切面

简介:

前面了解了典型的AOP基于配置的使用方法,下面介绍下如何依赖于注解来实现AOP。

基于注解降低了配置文件的复杂程度,但是引入了程序间的耦合,其中的优劣待用户自己判断了。

需要注意的是,确定AspectJ与JDK之间的版本,否则会报错,详情请见

  首先看一下基于注解的切面类,这时的切面不仅仅是一个POJO类了,与AOP进行了紧密的耦合。但是配置过程和方式都与原来的方式差不多。

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

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;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Audience {
    @Pointcut("execution(* com.spring.test.chap44.Instrumentalist.perform(..))")
    public void performance(){}
    
    @Before("performance()")
    public void takeSeats(){
        System.out.println("takeSeats()");
    }
    @Before("performance()")
    public void turnOffCellphones(){
        System.out.println("turnOffCellphones()");
    }
    @AfterReturning("performance()")
    public void applaud(){
        System.out.println("applaud()");
    }
    @AfterThrowing("performance()")
    public void demandRefund(){
        System.out.println("demandRefund()");
    }
}
复制代码

  接下来是其他一些必不可少的类:

  切点接口类:

package com.spring.test.chap44;

public interface Performer {
    public void perform();
}

  切点实现类:

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

import org.springframework.stereotype.Component;

@Component
public class Instrumentalist implements Performer{
    public void perform() {
        System.out.println("__________ perform ___________");
    }
}
复制代码

  测试类:

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

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

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

  下面是重点的配置文件

  此时的配置文件注意要使spring知道哪一个是普通的bean,哪一个是通知。因此需要加上一个属性,保证AOP自动的识别通知。

<aop:aspectj-autoproxy proxy-target-class="true"/>

  配置文件如下:

复制代码
<?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:context="http://www.springframework.org/schema/context"
    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-3.0.xsd
                         http://www.springframework.org/schema/context
                         http://www.springframework.org/schema/context/spring-context-3.0.xsd
                         http://www.springframework.org/schema/tx
                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                         http://www.springframework.org/schema/aop 
                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <bean id="xingoo" class="com.spring.test.chap44.Instrumentalist"/>
    <bean id="audience" class="com.spring.test.chap44.Audience" />
    <aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
复制代码

  执行结果如下:

turnOffCellphones()
takeSeats()
__________ perform ___________
applaud()

 

  如果需要使用around只需要在切面中添加如下的代码就可以了:

复制代码
    @Around("performance()")
    public void watchPerformance(ProceedingJoinPoint joinpoint){
        try{
            System.out.println("11111");
            
            long start = System.currentTimeMillis();
            
            joinpoint.proceed();
            
            long end = System.currentTimeMillis();
            
            System.out.println("time—— "+(end-start)+" millinseconds");
            System.out.println("22222");
        }catch(Throwable t){
            System.out.println("in watchPerformance Throwable()");
        }
    }
复制代码

   对于参数的传递的通知,也与原先通过配置的差不多

  在切面中配置好切点的方法,注意带上参数

复制代码
    private String str;
    @Pointcut("execution(* com.spring.test.chap44.Instrumentalist.perform(String)) && args(str)")
    public void performance(String str){}
    
    @Before("performance(str)")
    public void takeSeats(String str){
        System.out.println("takeSeats()"+str);
    }
复制代码

  其他的基本都不用动了,只要把切点的方法,修改成带有参数的就可以了

public class Instrumentalist implements Performer{
    public void perform(String str) {
        System.out.println("__________ perform ___________" + str);
    }
}

 

本文转自博客园xingoo的博客,原文链接:【Spring实战】—— 13 AspectJ注解切面,如需转载请自行联系原博主。
相关文章
|
10天前
|
XML Java 数据格式
Spring从入门到入土(bean的一些子标签及注解的使用)
本文详细介绍了Spring框架中Bean的创建和使用,包括使用XML配置文件中的标签和注解来创建和管理Bean,以及如何通过构造器、Setter方法和属性注入来配置Bean。
45 9
Spring从入门到入土(bean的一些子标签及注解的使用)
|
3天前
|
架构师 Java 开发者
得物面试:Springboot自动装配机制是什么?如何控制一个bean 是否加载,使用什么注解?
在40岁老架构师尼恩的读者交流群中,近期多位读者成功获得了知名互联网企业的面试机会,如得物、阿里、滴滴等。然而,面对“Spring Boot自动装配机制”等核心面试题,部分读者因准备不足而未能顺利通过。为此,尼恩团队将系统化梳理和总结这一主题,帮助大家全面提升技术水平,让面试官“爱到不能自已”。
得物面试:Springboot自动装配机制是什么?如何控制一个bean 是否加载,使用什么注解?
|
7天前
|
XML Java 数据库
Spring boot的最全注解
Spring boot的最全注解
|
8天前
|
JSON NoSQL Java
springBoot:jwt&redis&文件操作&常见请求错误代码&参数注解 (九)
该文档涵盖JWT(JSON Web Token)的组成、依赖、工具类创建及拦截器配置,并介绍了Redis的依赖配置与文件操作相关功能,包括文件上传、下载、删除及批量删除的方法。同时,文档还列举了常见的HTTP请求错误代码及其含义,并详细解释了@RequestParam与@PathVariable等参数注解的区别与用法。
|
8天前
|
Java API Spring
springBoot:注解&封装类&异常类&登录实现类 (八)
本文介绍了Spring Boot项目中的一些关键代码片段,包括使用`@PathVariable`绑定路径参数、创建封装类Result和异常处理类GlobalException、定义常量接口Constants、自定义异常ServiceException以及实现用户登录功能。通过这些代码,展示了如何构建RESTful API,处理请求参数,统一返回结果格式,以及全局异常处理等核心功能。
|
11天前
|
Java 编译器 Spring
Spring AOP 和 AspectJ 的区别
Spring AOP和AspectJ AOP都是面向切面编程(AOP)的实现,但它们在实现方式、灵活性、依赖性、性能和使用场景等方面存在显著区别。‌
27 2
|
12天前
|
Java 数据库连接 Spring
【2021Spring编程实战笔记】Spring开发分享~(下)
【2021Spring编程实战笔记】Spring开发分享~(下)
21 1
|
2天前
|
XML Java 数据格式
Spring IOC容器的深度解析及实战应用
【10月更文挑战第14天】在软件工程中,随着系统规模的扩大,对象间的依赖关系变得越来越复杂,这导致了系统的高耦合度,增加了开发和维护的难度。为解决这一问题,Michael Mattson在1996年提出了IOC(Inversion of Control,控制反转)理论,旨在降低对象间的耦合度,提高系统的灵活性和可维护性。Spring框架正是基于这一理论,通过IOC容器实现了对象间的依赖注入和生命周期管理。
12 0
|
8天前
|
XML Java 数据格式
手动开发-简单的Spring基于注解配置的程序--源码解析
手动开发-简单的Spring基于注解配置的程序--源码解析
22 0
|
12天前
|
XML Java 数据格式
Java-spring注解的作用
Java-spring注解的作用
15 0