今天对 Spring AOP的使用作个简单说明。spring
一、AOP的实现方式: 1)XML 2)注解maven
二、在上面两种实现方式中,如今注解使用的愈来愈普遍;它的主要好处是写起来比xml要方便的多,但也有解分散到不少类中,很差管理和维护的缺点,今天主要分享经过注解的实现方式。 主要注解有: @Aspect、@Pointcut 和通知,见下图:spring-boot
![![]单元测试
三、注解说明: 1)@Aspect:类级别注解,用来标志类为切面类。测试
1)Pointcut表达式: (1)designators (指示器):经过哪些方法和方式,去匹配类和方法;如executionthis
(2)Wildcards:经过通配符描述方法,如“* .. +”等代理
(3)operators:如||、&&、!code
2)Adivice注解(5种)xml
四、使用的简单例子:对象
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)运行结果: