Spring(使用Annotation方式的AOP)

本文介绍如何使用 Spring AOP 和 AspectJ 实现方法调用前的日志记录功能。通过配置 XML 文件,定义切面及切入点表达式,演示了在特定方法执行前触发自定义逻辑的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.配置XML文件

  <?xml version="1.0" encoding="UTF-8"?>

<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
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           ">
           
    <context:annotation-config/>
    <!-- 扫描com.daoan下面的所有包,包括子包 -->
    <context:component-scan base-package="com.daoan"/>

<aop:aspectj-autoproxy/> </beans>
  <!-- 如果这里写
<aop:aspectj-autoproxy/>
没有提示需要引入相关的xsd文件 -->
  
  查找Spring-aop-2.5.xsd(C:\spring-framework-2.5.6-with-dependencies\spring-framework-2.5.6\dist\resources)
  

key:http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

写一个逻辑来测试

 需要引入相应的jar

 

package com.daoan.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogIntercetor {
    //(在save()方法执行之前先执行before()方法,如果需要把该逻辑织入到某个类的某个方法上,那个对象必须是spring管理起来的)
    @Before("execution(public void com.daoan.dao.impl.UserDAOImpl.save(com.daoan.model.User))")
    public void before() {
        System.out.println("method start");
    }
}

 

前进固然艰难,且代价惨重,而退回去舒服,却要吞咽人生致命的毒药!

遇到问题不能想着逃,如果总是逃避,那将永远都是你的问题,永远无法解答!

 

转载于:https://www.cnblogs.com/xdalsh/p/8440430.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值