【Spring】简单的Spring AOP注解示例
如何配置,以及相关知识
引入相关包:
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
<aspectj.version>1.6.11</aspectj.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
在Spring配置文件开启注解、AspectJ支持、扫描基础包:
<?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-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 开启注解 -->
<context:annotation-config/>
<!-- AspectJ支持 -->
<aop:aspectj-autoproxy />
<!-- 扫描基础包 -->
<context:component-scan base-package="com.nicchagil.springaop" />
</beans>
写两个测试的Service:
package com.nicchagil.springaop;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void query(Integer id) {
System.out.println("UserService.query()...");
}
}
package com.nicchagil.springaop;
import org.springframework.stereotype.Service;
@Service
public class FunctionService {
public void query() {
System.out.println("FunctionService.query()...");
}
}
切面的信息:
package com.nicchagil.springaop;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
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;
@Aspect
@Component
public class MyAOP {
@Pointcut("execution(* com.nicchagil.springaop.*Service.query(..))")
public void myPointcut() {
}
@Before("myPointcut()")
public void myBefore(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs(); // 入参
System.out.println("Before. Args : " + Arrays.toString(args));
}
@AfterReturning("myPointcut()")
public void myAfterReturning() {
System.out.println("AfterReturning.");
}
@AfterThrowing("myPointcut()")
public void myAfterThrowing() {
System.out.println("AfterThrowing.");
}
}
下图可帮助理解通知(Advice)、切点(PointCut)、切面(Aspect)、织入(Weaving)各大术语:
入口类:
package com.nicchagil.springaop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HowToUse {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
UserService us = context.getBean("userService", UserService.class);
us.query(100);
FunctionService fs = context.getBean("functionService", FunctionService.class);
fs.query();
}
}
日志:
Before. Args : [100]
UserService.query()...
AfterReturning.
Before. Args : []
FunctionService.query()...
AfterReturning.
常用的AOP
添加AOP:
package com.nicchagil.exercise.springbootexercise.aop;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
@Aspect
@Configuration
public class AopExample {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(* com.nicchagil.exercise.springbootexercise.service..*.*(..))")
public void serviceAllMethodPointcut() {
}
@Around("serviceAllMethodPointcut()")
public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
/* 获取常用的对象 */
Object targetObject = proceedingJoinPoint.getThis(); // 目标对象
Object[] args = proceedingJoinPoint.getArgs(); // 入参
Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); // 方法对象
this.logger.info("@Around targetObject : {}, args : {}, method : {}", targetObject, args, method);
Object result = proceedingJoinPoint.proceed(); // 执行被拦截的代码
this.logger.info("@Around result : {}", result);
return result; // 记得返回
}
@Before("serviceAllMethodPointcut()")
public void myBefore(JoinPoint joinPoint) {
/* 获取常用的对象 */
Object targetObject = joinPoint.getThis(); // 目标对象
Object[] args = joinPoint.getArgs(); // 入参
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); // 方法对象
this.logger.info("@Before targetObject : {}, args : {}, method : {}", targetObject, args, method);
}
@AfterReturning(value = "serviceAllMethodPointcut()", returning = "returningObject")
public void myAfterReturning(JoinPoint joinPoint, Object returningObject) {
/* 获取常用的对象 */
Object targetObject = joinPoint.getThis(); // 目标对象
Object[] args = joinPoint.getArgs(); // 入参
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); // 方法对象
this.logger.info("@AfterReturning targetObject : {}, args : {}, method : {}, returningObject : {}",
targetObject, args, method, returningObject);
}
@AfterThrowing(value = "serviceAllMethodPointcut()", throwing="throwable")
public void myAfterThrowing(JoinPoint joinPoint, Throwable throwable) {
/* 获取常用的对象 */
Object targetObject = joinPoint.getThis(); // 目标对象
Object[] args = joinPoint.getArgs(); // 入参
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); // 方法对象
this.logger.info("@AfterThrowing targetObject : {}, args : {}, method : {}, throwable : {}",
targetObject, args, method, throwable);
}
}
日志打印(异常的情况就没演示了):
2018-01-06 10:34:13.207 INFO 7176 --- [ main] Example$$EnhancerBySpringCGLIB$$ed744e46 : @Around targetObject : com.nicchagil.exercise.springbootexercise.service.UserService@67b100fe, args : [1], method : public com.nicchagil.exercise.springbootexercise.mapper.entity.User com.nicchagil.exercise.springbootexercise.service.UserService.selectByPrimaryKey(java.lang.Long)
2018-01-06 10:34:13.223 INFO 7176 --- [ main] Example$$EnhancerBySpringCGLIB$$ed744e46 : @Before targetObject : com.nicchagil.exercise.springbootexercise.service.UserService@67b100fe, args : [1], method : public com.nicchagil.exercise.springbootexercise.mapper.entity.User com.nicchagil.exercise.springbootexercise.service.UserService.selectByPrimaryKey(java.lang.Long)
2018-01-06 10:34:13.582 INFO 7176 --- [ main] Example$$EnhancerBySpringCGLIB$$ed744e46 : @Around result : User [id=1, name=Nick Huang, age=20, createTime=Sat Nov 25 00:00:00 CST 2017]
2018-01-06 10:34:13.582 INFO 7176 --- [ main] Example$$EnhancerBySpringCGLIB$$ed744e46 : @AfterReturning targetObject : com.nicchagil.exercise.springbootexercise.service.UserService@67b100fe, args : [1], method : public com.nicchagil.exercise.springbootexercise.mapper.entity.User com.nicchagil.exercise.springbootexercise.service.UserService.selectByPrimaryKey(java.lang.Long), returningObject : User [id=1, name=Nick Huang, age=20, createTime=Sat Nov 25 00:00:00 CST 2017]
【Spring】简单的Spring AOP注解示例的更多相关文章
- Spring第三天——AOP注解实现与事务管理
大致内容: aspectJ的aop操作(基于注解,对比day02配置操作)(会用) *jdbcTemplate操作(实现CRUD) *spring配置连接池 *spring事务管理 一.AspectJ ...
- 【译】Spring 4 @PropertySource和@Value注解示例
前言 译文链接:http://websystique.com/spring/spring-propertysource-value-annotations-example/ 本篇文章将展示如何通过@P ...
- Spring AOP注解形式简单实现
实现步骤: 1:导入类扫描的注解解析器 命名空间:xmlns:context="http://www.springframework.org/schema/context" xsi ...
- 简单理解Spring之IOC和AOP及代码示例
Spring是一个开源框架,主要实现两件事,IOC(控制反转)和AOP(面向切面编程). IOC 控制反转,也可以称为依赖倒置. 所谓依赖,从程序的角度看,就是比如A要调用B的方法,那么A就依赖于B, ...
- JAVA WEB快速入门之通过一个简单的Spring项目了解Spring的核心(AOP、IOC)
接上篇<JAVA WEB快速入门之从编写一个JSP WEB网站了解JSP WEB网站的基本结构.调试.部署>,通过一个简单的JSP WEB网站了解了JAVA WEB相关的知识,比如:Ser ...
- Spring AOP—注解配置方法的使用
Spring除了支持Schema方式配置AOP,还支持注解方式:使用@AspectJ风格的切面声明. 1 启用对@AspectJ的支持 Spring默认不支持@AspectJ风格的切面声明,为了支持需 ...
- 【译】Spring 4 @Profile注解示例
前言 译文链接:http://websystique.com/spring/spring-profile-example/ 本文将探索Spring中的@Profile注解,可以实现不同环境(开发.测试 ...
- Spring详解(六)------AOP 注解
上一篇博客我们讲解了 AspectJ 框架如何实现 AOP,然后具体的实现方式我们是通过 xml 来进行配置的.xml 方式思路清晰,便于理解,但是书写过于麻烦.这篇博客我们将用 注解 的方式来进行 ...
- Spring框架-IOC和AOP简单总结
参考博客: https://blog.csdn.net/qq_22583741/article/details/79589910 1.Spring框架是什么,为什么,怎么用 1.1 Spring框架是 ...
随机推荐
- NGINX 配置 SSL 双向认证
对于 NGINX 的 HTTPS 配置,通常情况下我们只需要实现服务端认证就行,因为浏览器内置了一些受信任的证书颁发机构(CA),服务器端只需要拿到这些机构颁发的证书并配置好,浏览器会自己校验证书的可 ...
- python 的var_dump
from __future__ import print_function from types import NoneType __author__ = "Shamim Hasnath&q ...
- anjularjs常用的内置方法
1.$apply anjularjs通过$apply方法去执行脏检查,及时告诉model绑定变量更新. 示例:定义一个date变量显示在页面上,它的控制器是firstCtrl,这个date变量有一个时 ...
- 《storm实战-构建大数据实时计算读书笔记》
自己的思考: 1.接收任务到任务的分发和协调 nimbus.supervisor.zookeeper 2.高容错性 各个组件都是无状态的,状态 ...
- docker在centos7下的一些坑
在centos的docker上安装mysql提示chown mod /var/lib/mysql permission denied,通过下面的方法1解决. 在centos上挂载数据卷,在容器内部访问 ...
- android 中获取当前焦点所在屏幕中的位置 view.getLocationOnScreen(location)
final int[] location = new int[2]; view.getLocationOnScreen(location); final int[] location = new in ...
- Spark on Yarn:java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://localhost\\db_instance_name:1433;databaseName=db_name
本文只是针对当前特定环境下,出现的问题找不到sqljdbc驱动的案例.具体出现原因,可能是spark版本问题,也可能是集群配置问题. yarn-client方式下: 通过--jars参数指定驱动文件位 ...
- linux---------------centos6.4安装完了以后敲ifconfig,没有局域网ip。解决如下
1.vim /etc/sysconfig/network-scripts/ifcfg-eth0 进入linux然后进入这个文件里面如下: DEVICE=eth0HWADDR=00:0C:29:92:F ...
- windows下的host文件在哪里?做什么用的?
在Window系统中有个Hosts文件(没有后缀名),在Windows98系统下该文件在Windows目录,在Windows2000/XP系统中位于C:\Winnt\System32\Drivers\ ...
- 4-Server安全配置
0-禁止root使用ssh登入 vim /etc/ssh/sshd_config寻找:PermitRootLogin yes改为:PermitRootLogin nosystemctl restart ...