posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

方式一,实现MethodBeforeAdvice,AfterReturningAdvice接口,在applicationContext.xml中注入bean,创建切入点,配置环绕增加,xml需要引入aop约束。
public void before(Method method, Object[] objects, Object o)//目标方法,方法参数,目标类
public void afterReturning(Object o, Method method, Object[] objects, Object o1)//目标方法返回值,目标方法,方法参数,目标类

1
2
3
4
5
6
7
8
<aop:config>
        <!-- 切入点 execution(返回类型 类.方法名(参数列表))-->
        <!--第一个*代表所有类型,第二个*代表类中所有方法,(..)代表任意参数-->
        <aop:pointcut id="pointcut" expression="execution(* com.jay.service.UserServiceImpl.*(..))"/>
        <!--执行环绕增加-->
        <aop:advisor advice-ref="logBefore" pointcut-ref="pointcut"></aop:advisor>
        <aop:advisor advice-ref="logAfter" pointcut-ref="pointcut"></aop:advisor>
</aop:config>

 方式二,自定义类和方法,方法中无法通过参数自动获取目标类的相关信息

1
2
3
4
5
6
7
<aop:config>
    <aop:aspect ref="log">
        <aop:pointcut id="point" expression="execution(* com.jay.service.UserService.*(..))"/>
        <aop:before method="before" pointcut-ref="point" />
        <aop:after method="after" pointcut-ref="point" />
    </aop:aspect>
</aop:config>

 方式三,注解实现AOP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.jay.service;
 
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
 
@Aspect
public class AnnotationPointCut {
    @Before("execution(* com.jay.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("前...");
    }
    @After("execution(* com.jay.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("后...");
    }
}

 配置:

1
2
3
4
<!--方式三,注解实现AOP-->
<bean id="annotationPointCut" class="com.jay.service.AnnotationPointCut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>

 测试:

1
2
3
4
5
6
7
@Test
public void test3() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //代理的是一类业务,需要使用接口
        UserService m = context.getBean("userService",UserService.class);
        m.getUser("jay.x");
}

 要引入依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>

posted on   邢帅杰  阅读(217)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
历史上的今天:
2015-07-30 WCF、Net remoting、Web service概念及区别
2015-07-30 select into tb_temp2 from tb_temp1 创建临时表实现上一个、下一个功能,使用完毕就删除临时表
点击右上角即可分享
微信分享提示