Spring AOP的主要功能相信大家都知道,日志记录、权限校验等等。

用法就是定义一个切入点(Pointcut),定义一个通知(Advice),然后设置通知在该切入点上执行的方式(前置、后置、环绕等)。

只不过一直没想过切入点还可以是注解。

下面直接进入节奏

1、打开STS,新建一个Spring Starter Project。如果不清楚STS是什么,可以参考我的 Spring Tools Suite (STS) 简介,几分钟的事。

Starter模块选择web、aop,其实我还选了一个Devtools模块,不过对这个示例来说没有区别。

新建完成后,外观是这样的:

2、新建一个注解 cn.larry.spring.annotation.Log

注意:STS有新建注解的选项(没注意过Eclipse有没有~~),可以直接选择保留策略和目标。当然也可以新建好空白注解之后添加。

新建的注解内容如下:

package cn.larry.spring.annotation;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target; @Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface Log { }

由于只是案例示范,这里只添加一个注解参数 value 即可。如下:

package cn.larry.spring.annotation;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target; @Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface Log {
String value() default "我是日志注解";
}

3、接下来就该AOP登场啦,新建一个类 cn.larry.spring.aspect.LogAspect。并添加@Component和@Aspect注解 -- 这是因为@Aspect只能作用在bean上。如下:

package cn.larry.spring.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component; @Component
@Aspect
public class LogAspect { }

然后定义一个Pointcut,如下:

@Pointcut("@annotation(cn.larry.spring.annotation.Log)")
private void cut() { }

再定义一个Advice,如下:

@Around("cut()")
public void advice(ProceedingJoinPoint joinPoint){
System.out.println("环绕通知之开始");
try {
joinPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("环绕通知之结束");
}

至此,一个简单的Aspect就创建完毕。

注:本来我想直接使用 新建Aspect,不过提示本项目不是一个Aspect项目,遂放弃。想了一下,大概是因为Spring仅借用了注解的缘故。

下面就是该Aspect的使用了。

4、新建一个Service,并添加一个run方法(方法名随意),然后在该方法上使用注解@Log:

package cn.larry.spring.service;

import org.springframework.stereotype.Service;

import cn.larry.spring.annotation.Log;

@Service
public class DemoService {
@Log
public void run(){
System.out.println("----我是cn.larry.spring.service.DemoService.run()----");
}
}

5、有了方法,还需要调用,所以新建一个Controller,注入Service,并调用其方法:

package cn.larry.spring.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import cn.larry.spring.service.DemoService; @RestController
@RequestMapping("/aop")
public class AopController {
@Autowired
private DemoService demoService;
@RequestMapping public String run(){
demoService.run();
return "Controller completed!";
}
}

至此,一个简单的示例就完成了,以Spring Boot App启动,然后访问  http://localhost:8080/aop 即可。控制台内容如下:

当然,这是最简单的示例,实际需求通常比这个复杂,不过不外乎获取注解的参数,然后根据参数内容进行操作。甚至可以获取被注解的方法,再获取该方法的参数,然后根据参数再进行不同的操作。

如有意,欢迎探讨。

补充:

@AspectJ 是用被注解的Java类来声明切面的一种方式(另一种方式就是xml设置),但是Spring只是借用它的注解,本质还是Spring的东西。原文如下:

@AspectJ refers to a style of declaring aspects as regular Java classes annotated with annotations.
The @AspectJ style was introduced by the AspectJ project as part of the AspectJ 5 release.
Spring interprets the same annotations as AspectJ 5, using a library supplied by AspectJ for pointcut parsing and matching.
The AOP runtime is still pure Spring AOP though, and there is no dependency on the AspectJ compiler or weaver.

利用Spring AOP和自定义注解实现日志功能的更多相关文章

  1. 运用Spring Aop,一个注解实现日志记录

    运用Spring Aop,一个注解实现日志记录 1. 介绍 我们都知道Spring框架的两大特性分别是 IOC (控制反转)和 AOP (面向切面),这个是每一个Spring学习视频里面一开始都会提到 ...

  2. 我使用Spring AOP实现了用户操作日志功能

    我使用Spring AOP实现了用户操作日志功能 今天答辩完了,复盘了一下系统,发现还是有一些东西值得拿出来和大家分享一下. 需求分析 系统需要对用户的操作进行记录,方便未来溯源 首先想到的就是在每个 ...

  3. spring AOP 和自定义注解进行身份验证

    一个SSH的项目(springmvc+hibernate),需要提供接口给app使用.首先考虑的就是权限问题,app要遵循极简模式,部分内容无需验证,用过滤器不能解决某些无需验证的方法 所以最终选择用 ...

  4. 利用spring AOP实现每个请求的日志输出

    前提条件: 除了spring相关jar包外,还需要引入aspectj包. <dependency> <groupId>org.aspectj</groupId> & ...

  5. Spring aop 拦截自定义注解+分组验证参数

    import com.hsq.common.enums.ResponseState;import com.hsq.common.response.ResponseVO;import org.aspec ...

  6. 利用Spring AOP自定义注解解决日志和签名校验

    转载:http://www.cnblogs.com/shipengzhi/articles/2716004.html 一.需解决的问题 部分API有签名参数(signature),Passport首先 ...

  7. (转)利用Spring AOP自定义注解解决日志和签名校验

    一.需解决的问题 部分API有签名参数(signature),Passport首先对签名进行校验,校验通过才会执行实现方法. 第一种实现方式(Origin):在需要签名校验的接口里写校验的代码,例如: ...

  8. 化繁就简,如何利用Spring AOP快速实现系统日志

    1.引言 有关Spring AOP的概念就不细讲了,网上这样的文章一大堆,要讲我也不会比别人讲得更好,所以就不啰嗦了. 为什么要用Spring AOP呢?少写代码.专注自身业务逻辑实现(关注本身的业务 ...

  9. Spring Boot实现自定义注解

    在Spring Boot项目中可以使用AOP实现自定义注解,从而实现统一.侵入性小的自定义功能. 实现自定义注解的过程也比较简单,只需要3步,下面实现一个统一打印日志的自定义注解: 1. 引入AOP依 ...

随机推荐

  1. ubuntu的apt-get提示资源被锁定

    一.错误提示 E: Could not : Resource temporarily unavailable) E: Unable to lock the administration directo ...

  2. 连接mysql-front数据库出现‘执行错误1251’的解决办法(有效)

    原因是MySQL8.0版本的加密方式和MySQL5.0的不一样,连接会报错. 解决方法:更改加密方式 控制台中先连接mysql: 再输入: ALTER USER 'root'@'localhost' ...

  3. 强制删除一个Windows服务

    一个挂起的服务如下图所示,该服务相关的所有按钮都被禁用,包括启动.停止.暂停和恢复. 要停止这个服务,首先记住这个服务的名称,在这里是 ‘EntropySoftCFS’. 然后打开命令行窗口,运行 s ...

  4. MongoDB创建索引(不锁库方法)

    db.collection.createIndex( { a: 1 }, { background: true } )https://docs.mongodb.org/manual/tutorial/ ...

  5. Executor , ExecutorService 和 Executors

    三者的主要区别和关系如下: Executor 和 ExecutorService 这两个接口主要的区别是:ExecutorService 接口继承了 Executor 接口,是 Executor 的子 ...

  6. linux命令(32):cat

    1.cat 显示文件连接文件内容的工具: cat 是一个文本文件查看和连接工具.查看一个文件的内容,用cat比较简单,就是cat 后面直接接文件名. 比如: [root@localhost ~]# c ...

  7. Win7  CMD大全

    Win7  CMD大全  compmgmt.msc---计算机管理 conf—-启动 netmeeting charmap–-启动字符映射表 calc—-启动计算器 chkdsk.exe–-Chkds ...

  8. electron 创建窗口2

    /** * 窗口管理类,单例,负责创建所有窗口,保存窗口实例 */ const path = require('path'); const os = require('os'); const EucW ...

  9. CSocket类的使用

    重点介绍一个MFC中CSocket类的使用 1.创建套接字 使用CSocket类创建套接字对象是通过该类的构造函数创建的.其原型如下: CSocket::CSocket(); 例如,用户创建CSock ...

  10. iPython网页启动

    安装必要的软件包: pip install "ipython[all]"   启动命令:ipython notebook --inline=pylib 自动采用默认浏览器打开 ht ...