【Spring进阶系列丨第十篇】基于注解的面向切面编程(AOP)详解

文章目录

一、基于注解的AOP

1、配置Spring环境

xml 复制代码
<dependencies>
        <!-- 导入Spring的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
</dependencies>

2、在beans.xml文件中定义AOP约束

xml 复制代码
<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
        https://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">
</beans>

3、定义记录日志的类【切面】

java 复制代码
@Component("logger")
@Aspect // 表示的是一个切面
public class Logger {
  	
    // 目的:在调用业务方法之前进行增强【前置通知】
    @Before("execution(* cn.bdqn.service.impl.*.*(..))")
    public void beforePrintLog(){
        System.out.println("前置通知----beforePrintLog---开始打印日志啦");
    }
  
  	// 后置通知
    @AfterReturning("execution(* cn.bdqn.service.impl.*.*(..))")
    public void afterReturningPrintLog(){
        System.out.println("后置通知----afterReturningPrintLog");
    }
}

​ 注意,该类的两个细节:

a、@Component注解向容器中注册一个Bean。

b、@Aspect注解表示这个是一个切面类。

c、@Before注解表示的是这个是前置增强/前置通知。

4、定义Bean

java 复制代码
package cn.bdqn.domain;

public class User {

}
java 复制代码
package cn.bdqn.service;
public interface UserService {

    // 保存用户
    public void save(User user);
}
java 复制代码
package cn.bdqn.service.impl;
@Service("userService")	// 向容器中注册Bean
public class UserServiceImpl implements UserService {

    @Override
    public void save(User user) {

        System.out.println("保存用户啦");
    }
}

​ 注意:对于业务Bean,我们也需要通过@Service注解来向容器中注册。

5、在主配置文件中配置扫描的包

xml 复制代码
<beans>
	<context:component-scan base-package="cn.bdqn"/>
</beans>

6、在主配置文件中去开启AOP的注解支持

xml 复制代码
<beans>
	<aop:aspectj-autoproxy/>
</beans>

7、测试

java 复制代码
public class UserServiceTest {
    @Test
    public void testUserService() throws Exception{

        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        UserService userService = (UserService) ac.getBean("userService");

        userService.queryAll();
    }
}

8、优化改进

​ 问题:我们看到对于切面类中定义的通知,有一个共性问题是,切入点表达式是相同的 , 那我们在想能否也像xml配置的那样,把切入点表达式给抽取出来呢?答案是可以的,改造如下:

java 复制代码
@Component("logger")
@Aspect // 表示的是一个切面
public class Logger {

    @Pointcut("execution(* cn.bdqn.service.impl.*.*(..))")
    private void pt(){}


    // 目的:在调用业务方法之前进行增强【前置通知】
    @Before("pt()")
    public void beforePrintLog(){
        System.out.println("前置通知----beforePrintLog---开始打印日志啦");
    }

    // 演示的后置通知
    @AfterReturning("pt()")
    public void afterReturningPrintLog(){
        System.out.println("后置通知----afterReturningPrintLog");
    }
}

9、总结

  • 配置业务Bean

    java 复制代码
    @Service("userService")
    public class UserServiceImpl implements UserService{
      
    }
  • 配置切面Bean

  • 需要在切面类上定义@Aspect // 表示的是一个切面

    java 复制代码
    @Component("logger")
    @Aspect // 表示的是一个切面
    public class Logger {
      	
    }
  • 在切面类中的通知方法上定义相应的通知

    tex 复制代码
    @Before: 前置通知
    @AfterReturning:后置通知
    @AfterThrowing: 异常通知
    @After:最终通知
    @Around: 环绕通知
  • 定义切入点表达式

    java 复制代码
    @Before("execution(* cn.bdqn.service.impl.*.*(..))")
    public void beforePrintLog(){
        System.out.println("前置通知----beforePrintLog---开始打印日志啦");
    }
  • 在主配置文件中去开启AOP的注解

    aop:aspectj-autoproxy/


相关推荐
她说彩礼65万2 分钟前
Asp.net core appsettings.json` 和 `appsettings.Development.json`文件区别
后端·json·asp.net
用户21411832636027 分钟前
国产化算力实战:手把手教你在魔乐社区用华为昇腾 NPU 跑通模型推理
后端
IT_陈寒7 分钟前
SpringBoot性能飞跃:5个关键优化让你的应用吞吐量提升300%
前端·人工智能·后端
M1A110 分钟前
你的认知模式,决定了你的人生高度
后端
追逐时光者1 小时前
Everything替代工具,一款基于 .NET 开源免费、高效且用户友好文件搜索工具!
后端·.net
一个小白开发1 小时前
ip获取城市省份信息
java·tcp/ip
豆沙沙包?1 小时前
2025年--Lc170--H289. 生命游戏(矩阵)--Java版
java·游戏·矩阵
冬夜戏雪1 小时前
[学习日记][springboot 1-7][leetcode 6道]
java·开发语言·学习
讓丄帝愛伱1 小时前
idea 中 mapper.xml黄线警告怎么去掉
java·intellij-idea
QX_hao1 小时前
【Go】--数据类型
开发语言·后端·golang