iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >@Around注解怎么在Spring AOP中使用
  • 122
分享到

@Around注解怎么在Spring AOP中使用

2023-06-06 10:06:55 122人浏览 安东尼
摘要

这期内容当中小编将会给大家带来有关@Around注解怎么在spring aop中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。@Around注解可以用来在调用一个具体方法前和调用后来完成一些具体的任务

这期内容当中小编将会给大家带来有关@Around注解怎么在spring aop中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

@Around注解可以用来在调用一个具体方法前和调用后来完成一些具体的任务。

比如我们想在执行controller中方法前打印出请求参数,并在方法执行结束后来打印出响应值,这个时候,我们就可以借助于@Around注解来实现;

再比如我们想在执行方法时动态修改参数值等

类似功能的注解还有@Before等等,用到了Spring AOP切面思想,Spring AOP常用于拦截器、事务日志、权限验证等方面。

完整演示代码如下:

需要说明的是,在以下例子中,我们即可以只用@Around注解,并设置条件,见方法run1();也可以用@Pointcut和@Around联合注解,见方法pointCut2()和run2(),这2种用法是等价的。如果我们还想利用其进行参数的修改,则调用时必须用joinPoint.proceed(Object[] args)方法,将修改后的参数进行回传。如果用joinPoint.proceed()方法,则修改后的参数并不会真正被使用。

import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component; import javax.persistence.EntityManager;  @Component@Aspectpublic class ControllerAspect {  private static final Logger logger = LoggerFactory.getLogger(ControllerAspect.class);  @Autowired private EntityManager entityManager;   @Around("execution(* com.company.controller.*.*(..))") public Object run1(ProceedingJoinPoint joinPoint) throws Throwable {  //获取方法参数值数组  Object[] args = joinPoint.getArgs();  //得到其方法签名  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();  //获取方法参数类型数组  Class[] paramTypeArray = methodSignature.getParameterTypes();  if (EntityManager.class.isAssignableFrom(paramTypeArray[paramTypeArray.length - 1])) {   //如果方法的参数列表最后一个参数是entityManager类型,则给其赋值   args[args.length - 1] = entityManager;  }  logger.info("请求参数为{}",args);  //动态修改其参数  //注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args)  Object result = joinPoint.proceed(args);  logger.info("响应结果为{}",result);  //如果这里不返回result,则目标对象实际返回值会被置为null  return result; }  @Pointcut("execution(* com.company.controller.*.*(..))") public void pointCut2() {}  @Around("pointCut2()") public Object run2(ProceedingJoinPoint joinPoint) throws Throwable {  //获取方法参数值数组  Object[] args = joinPoint.getArgs();  //得到其方法签名  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();  //获取方法参数类型数组  Class[] paramTypeArray = methodSignature.getParameterTypes();  if (EntityManager.class.isAssignableFrom(paramTypeArray[paramTypeArray.length - 1])) {   //如果方法的参数列表最后一个参数是entityManager类型,则给其赋值   args[args.length - 1] = entityManager;  }  logger.info("请求参数为{}",args);  //动态修改其参数  //注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args)  Object result = joinPoint.proceed(args);  logger.info("响应结果为{}",result);  //如果这里不返回result,则目标对象实际返回值会被置为null  return result; }}

补充:Spring Aop实例(AOP 如此简单)@Aspect、@Around 注解方式配置

ioc相关的基本内容告一段落,本次介绍Spring的第二个特性,AOP,面向切面编程,术语听起来比较不容易理解,没关系,一切尽在实例中,让我们看一个简单的实例,就能明白。

实例

项目工程目录结构和代码获取地址

获取地址(版本Log将会注明每一个版本对应的课程)

https://GitHub.com/laiyijie/SpringLearning

目录结构

@Around注解怎么在Spring AOP中使用

运行工程

运行具有Main函数的 App.java

得到如下输出

method start time:1480223298250userHellomethod end time:1480223299250

项目详解

从App.java入手

App.java

package me.laiyijie.demo;import org.springframework.context.support.ClassPathXmlApplicationContext;import me.laiyijie.demo.service.HelloInterface;public class App { public static void main(String[] args) {  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("root-context.xml");  HelloInterface userService = context.getBean(HelloInterface.class);  userService.sayHello();  context.close(); }}

调用的是HelloInterface的sayHello方法

HelloInterface.java

package me.laiyijie.demo.service;public interface HelloInterface{  void sayHello(); }

其实现类为UserServiceImpl.java

UserServiceImpl.java

package me.laiyijie.demo.service;import org.springframework.stereotype.Service;@Servicepublic class UserServiceImpl implements HelloInterface { public void sayHello() {  try {   Thread.sleep(1000);  } catch (InterruptedException e) {   // TODO Auto-generated catch block   e.printStackTrace();  }  System.out.println("userHello"); } }

诶?情况跟我们看到的代码有出入?

sayHello 应该只输出 userHello,前后两行输出从何出现?

在Main函数中找不到一点儿线索!

这就是AOP的一个强大特性:

无侵入性,不改变原有的代码,却能增加功能!

那么究竟是如何增加功能的呢?

让我们看看TimeMonitor.java

TimeMonitor.java

package me.laiyijie.demo.aop;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Service;@Service@Aspectpublic class TimeMonitor { @Around("execution(* me.laiyijie.demo.service.UserServiceImpl.sayHello(..))") public void monitorAround(ProceedingJoinPoint pjp) throws Throwable {  System.out.println("method start time:" + System.currentTimeMillis());  Object re = pjp.proceed();  System.out.println("method end time:" + System.currentTimeMillis()); }}

终于看到了 method start time:1480223298250 和 method end time:1480223299250这两行输出是从哪儿出现的了!

让我们来仔细解读一下这个类

类有两个注释,分别是@Service和@Aspect,第一个注解是使得TimeMonitor受Spring托管并实例化。@Aspect就是使得这个类具有AOP功能(你可以这样理解)两个注解缺一不可

类里面只有一个方法,名字叫做monitorAroud,其实就是为了检测函数执行时间的!

那么关键点来了,两个输出语句是怎么插入到sayHello方法的前后的呢!

看这个注解:

@Around("execution(* me.laiyijie.demo.service.UserServiceImpl.sayHello(..))")

@Around表示包围一个函数,也就是可以在函数执行前做一些事情,也可以在函数执行后做一些事情

execution(* me.laiyijie.demo.service.UserServiceImpl.sayHello(..))

这个比较好理解,就是使用表达式的方式指定了要对哪个函数进行包围!(除了execution以外还有很多,可以搜索AspectJ语法来学习

也就是说,这个注解完整的说明了,应该在函数的什么位置插入变化,也就是所谓的切点

之后是函数的定义:

public Object monitorAround(ProceedingJoinPoint pjp)

这里引入了ProceedingJoinPoint,在使用了@Around之后可以带入这个参数,代表的其实就是sayHello这个函数,不过做了一些封装

而 Object re = pjp.proceed(); 就是相当于执行了 sayHello方法!

剩下的代码就不用过多解释了,就是在执行这个函数的前后分别进行了系统时间的获取。

我们把这个函数体,也就是定义了要做那些事情的代码,称作增强

而包含切点和增强结合起来就称作切面

面向切面由此而来!

Spring AOP 开启需要的配置

需要配置两项

pom.xml增加依赖(因为要用到AOP还需要不同的jar包)

root-context.xml中增加切面相关配置

root-context.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="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-4.3.xsd  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">   <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <context:component-scan base-package="me.laiyijie.demo"></context:component-scan></beans>

root-context.xml 增加了两行

xmlns:aop="http://www.springframework.org/schema/aop"

代表加入命名空间

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

使用1中引入的aop命名空间开起自动代理(自动代理具体含义后续慢慢解释,简单的理解就是AOP的实现是依靠自动代理实现的)

pom.xml

<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.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>me.laiyijie</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <dependencies>  <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->  <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-context</artifactId>   <version>4.3.2.RELEASE</version>  </dependency>    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->  <dependency>   <groupId>org.aspectj</groupId>   <artifactId>aspectjweaver</artifactId>   <version>1.8.9</version>  </dependency> </dependencies></project>

增加了一个依赖

AspectJ 一个强大的AOP框架,也就是@Aspect和@Around以及ProceedingJoinPoint这些注解和方法的提供者

上述就是小编为大家分享的@Around注解怎么在Spring AOP中使用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注编程网精选频道。

--结束END--

本文标题: @Around注解怎么在Spring AOP中使用

本文链接: https://www.lsjlt.com/news/246387.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • @Around注解怎么在Spring AOP中使用
    这期内容当中小编将会给大家带来有关@Around注解怎么在Spring AOP中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。@Around注解可以用来在调用一个具体方法前和调用后来完成一些具体的任务...
    99+
    2023-06-06
  • 在Spring中AOP怎么使用注解来实现
    这期内容当中小编将会给大家带来有关在Spring中AOP怎么使用注解来实现,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。spring对AOP的实现提供了很好的支持。下面我们就使用Spring的注解来完成A...
    99+
    2023-05-31
    spring aop
  • 怎么在spring中实现一个aop注解
    今天就跟大家聊聊有关怎么在spring中实现一个aop注解,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。注解方式实现aop我们主要分为如下几个步骤:  1.在切面类(为切点服务的类)...
    99+
    2023-05-31
    spring aop
  • 在AOP中使用@Around后无返回值如何解决
    这篇文章给大家介绍在AOP中使用@Around后无返回值如何解决,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。改成如下即可:@Around("point_update()")public ...
    99+
    2023-06-06
  • 如何在Android中使用 AOP注解
    今天就跟大家聊聊有关如何在Android中使用 AOP注解,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。一、简介在Android 里面 注解主要用来干这么几件事:和编译器一起给你一些...
    99+
    2023-05-31
    android aop 注解
  • PropertySource注解怎么在Spring boot中使用
    本篇文章给大家分享的是有关PropertySource注解怎么在Spring boot中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。1.1. PropertySource...
    99+
    2023-05-30
    springboot propertysource
  • 使用Spring Aop如何配置AspectJ注解
    这篇文章将为大家详细讲解有关使用Spring Aop如何配置AspectJ注解,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。采用的jdk代理,接口和实现类代码请参考上篇博文。主要是将Aspe...
    99+
    2023-05-31
    springaop aspectj
  • Spring AOP中什么是半注解和全注解模式
    本篇文章为大家展示了Spring AOP中什么是半注解和全注解模式,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。<bean id="logUtils" ...
    99+
    2023-06-14
  • 怎么在不使用spring框架中使用aop的功能
    本篇文章为大家展示了怎么在不使用spring框架中使用aop的功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。Spring框架的AOP机制可以让开发者把业务流程中的通用功能抽取出来,单独编写功能代...
    99+
    2023-06-22
  • 使用Spring AOP 如何实现自定义注解
    这期内容当中小编将会给大家带来有关使用Spring AOP 如何实现自定义注解,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。在Maven中加入以下以依赖:<!-- Spring AOP + Aspe...
    99+
    2023-05-31
    springaop 注解
  • Spring AOP标签怎么使用
    这篇文章主要介绍“Spring AOP标签怎么使用”,在日常操作中,相信很多人在Spring AOP标签怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Spring AOP标签怎么使用”的疑惑有所帮助!...
    99+
    2023-06-02
  • Spring AOP如何在java项目中使用
    这篇文章将为大家详细讲解有关Spring AOP如何在java项目中使用 ,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。一、什么是AOP  AOP(Aspect Oriented ...
    99+
    2023-05-31
    java spring aop ava
  • 在Spring-Boot中怎么使用@Value注解注入集合类
    这篇文章主要讲解了“在Spring-Boot中怎么使用@Value注解注入集合类”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“在Spring-Boot中怎么使用@Value注解注入集合类”吧...
    99+
    2023-06-20
  • Spring @Cacheable注解中key怎么使用
    本篇内容介绍了“Spring @Cacheable注解中key怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!Spring ...
    99+
    2023-06-22
  • 如何在Spring中使用@Transactional注解
    这期内容当中小编将会给大家带来有关如何在Spring中使用@Transactional注解,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。@Transactionalservice A(){try...
    99+
    2023-06-15
  • Java Spring之基于注解的AOP怎么配置
    本篇内容主要讲解“Java Spring之基于注解的AOP怎么配置”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java Spring之基于注解的AOP怎么配置”吧!1 环境搭建1.1 第一步:...
    99+
    2023-07-05
  • @profile注解如何在spring中使用
    本篇文章给大家分享的是有关@profile注解如何在spring中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。首先是新建maven工程mvn archetype:gene...
    99+
    2023-05-30
    spring profile
  • Spring注解@Scope怎么使用
    @Scope注解用于指定Bean的作用域。Spring提供了多种作用域可选,包括Singleton、Prototype、Reques...
    99+
    2023-08-18
    Spring
  • spring @Component注解怎么使用
    @Component注解是用来标识一个类是Spring容器的一个组件。使用@Component注解的类会被Spring自动扫描并加入...
    99+
    2023-09-23
    spring
  • Spring的注解怎么使用
    这篇“Spring的注解怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Spring的注解怎么使用”文章吧。非全注解开...
    99+
    2023-06-29
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作