Spring AOP学习(二) -- Spring AOP的简单使用

今天对 Spring AOP的使用做个简单说明。

1、AOP的实现方式: 1)XML 2)注解

2、在上面两种实现方式中,现在注解使用的越来越广泛;它的主要好处是写起来比xml要方便的多,但也有解分散到很多类中,不好管理和维护的缺点,今天主要分享通过注解的实现方式。 主要注解有: @Aspect、@Pointcut 和通知,见下图:

![![Spring AOP主要注解]

3、注解说明: 1)@Aspect:类级别注解,用来标志类为切面类。

1)Pointcut表达式: (1)designators (指示器):通过哪些方法和方式,去匹配类和方法;如execution

  • 匹配方法:execution() exeution 表达式:execution(<修饰符模式>?<返回类型模式><方法名模式>(<参数模式>)<异常模式>?) 除了返回类型模式、方法名模式和参数模式外,其它项都是可选的(表达式的问号表示可以省略)。 eg:(* com.evan.crm.service..(..))中几个通配符的含义: 第一个 * —— 通配 随便率性返回值类型 第二个 * —— 通配包com.evan.crm.service下的任意class 第三个 * —— 通配包com.evan.crm.service下的任意class的任意方法 第四个 .. —— 通配 办法可以有0个或多个参数
  • 匹配注解:@target()、@args()、@within()、@annotation()
  • 匹配包、类型:within()
  • Within 举例 // 匹配TestService里面的所有方法 @Pointcut(“within(com.test.service.TestService)”) public void xxx(){}
  • 匹配对象:this()、bean()、target() this 匹配代理后; target 匹配代理前的; bean匹配所有符合规则的bean里头的方法。
  • 匹配参数:args()、execution()方法
  • 匹配注解:其中@annotation是方法级别的, @within和@target是类级别的,@args是参数级别的。

(2)Wildcards:通过通配符描述方法,如“* .. +”等

  • * : 匹配任意数量的字符
  • + : 匹配指定类及其子类
  • .. : 一般用于匹配人任意数的子包或参数

(3)operators:如||、&&、!

  • && : 与操作符,表示同时满足
  • || : 或操作符
  • ! : 非操作符

2)Adivice注解(5种)

  • @Before:方法前执行
  • @AfterReturning:运行方法后执行
  • @AfterThrowing:Throw后执行
  • @After:无论方法以何种方式结束,都会执行(类似于finally)
  • @Around:环绕执行

4、使用的简单例子:

1)新建springboo引入Spring AOP maven依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>

2)一个产品Service类,代码:

import org.springframework.stereotype.Service;

@Service
public class ProductService{

	public void saveProduct() {
		System.out.println("save product now ……");
	}

	public void deleteProduct() {
		System.out.println("delete product now ……");
	}
}

3)编写切面类:

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 AspectTest {

	@Pointcut("within(cn.exercise.service.impl.ProductService)")
	public void adminOnly() {
	}

	@Before("adminOnly()")
	public void before() {
		System.out.println("------------ @Aspect ###before");
	}
}

4)编写单元测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import cn.exercise.service.impl.ProductService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AopLeaningdemoApplicationTests {

	@Autowired
	private ProductService productService;
	
	@Test
	public void testAOP() {
		productService.saveProduct();
		productService.deleteProduct();
	}

}

5)运行结果:

运行结果图

猜你喜欢

转载自my.oschina.net/u/3696939/blog/1550940
今日推荐