通过注解的方式实现AOP

2022-07-06 09:06:41

使用注解实现AOP
1.创建切面类

packagecom.web.aop;importorg.aspectj.lang.annotation.After;importorg.aspectj.lang.annotation.Aspect;importorg.aspectj.lang.annotation.Before;importorg.springframework.stereotype.Component;@Aspect@ComponentpublicclassLog{@Before("execution(* com.web.pojo.Service.*(..))")publicvoidbefore(){System.out.println("============== Before Method =============");}@After("execution(* com.web.pojo.Service.*(..))")publicvoidafter(){System.out.println("============== After  Method =============");}}
@Component:将Bean注册到IOC容器中
@Aspect:声明一个切面类
@Before:方法执行前
@After:方法执行后

2.创建配置类

packagecom.web.config;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.EnableAspectJAutoProxy;@Configuration@ComponentScan("com.web.*")@EnableAspectJAutoProxypublicclassGlobalConfig{}
@Configuration:声明这是一个配置类
@CompontScan:对指定包下的Bean进行扫描
@EnableAspectJAutoProxy:启用@AspectJ支持

使用注解+xml的方式实现AOP

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"><context:component-scanbase-package="com.web.*"/><aop:aspectj-autoproxy/></beans>
<context:component-scan/>:对指定包下的bean进行扫描
<aop:aspectj-autoproxy/> :开启@Aspectj注解支持

切入点表达式

权限修饰符 权限定路径 方法名 (参数类型)
execution(public * *(..)):任何公共方法的执行
execution(* set*(..)):任何名称以set开头的方法的执行
execution(* com.xyz.service.AccountService.*(..)):由定义的任何方法的执行AccountService切面
execution(* com.xyz.service.*.*(..)):执行service包下的任何方法
execution(* com.xyz.service..*.*(..)):执行service或其子包之一中定义的任何方法
within(com.xyz.service.*):service包内的任何连接点
within(com.xyz.service..*):service包内的任何连接点或其中之一子包
this(com.xyz.service.AccountService):代理实现的任何连接点
  • 作者:冰点契约丶
  • 原文链接:https://blog.csdn.net/qq_52751442/article/details/122401957
    更新时间:2022-07-06 09:06:41