Spring自定义注解简单

本文介绍如何利用Spring AOP和自定义注解简化日志记录流程,通过四步实现方法级别的日志管理。

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

在实际开发中,很多时刻我们会有记录请求日志,定时任务日志等需求,在每个方法中都编写相同的代码去记录日志显然是不合理的。

Spring已经为我们提供了面向切面编程的思想,不妨简单的使用下自定义注解。

简单自定义注解分四步:

1:在配置中打开aop编程

 <!-- 自定义AOP -->

 <aop:aspectj-autoproxy proxy-target-class="true">

   <aop:include name="serviceAspect" />

 </aop:aspectj-autoproxy>

 <bean id = "serviceAspect" class="com.thc.tenantcenter.aspect.LogAspect"></bean>


2:编写自己自定义的注解 class指向的是切面解析类下文会有提到

 

 package com.thc.tenantcenter.aspect;

 import java.lang.annotation.Documented;

 import java.lang.annotation.ElementType;

 import java.lang.annotation.Inherited;

 import java.lang.annotation.Retention;

 import java.lang.annotation.RetentionPolicy;

 import java.lang.annotation.Target;

 @Target({ElementType.METHOD})

 @Retention(RetentionPolicy.RUNTIME)

 @Documented

 @Inherited

 public @interface LogAnnotation {

 

    String desc() default "打印日志";

 }

3:编写自己的切面实现类,就是上文所说的bean指向的路径

package com.thc.tenantcenter.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect //该注解标示该类为切面类 
@Component //注入依赖
public class LogAspect {  
  
    //标注该方法体为后置通知,当目标方法执行成功后执行该方法体  
    @AfterReturning("within(com.thc.tenantcenter..*) && @annotation(rl)")  
    public void addLogSuccess(JoinPoint jp, LogAnnotation rl){  
        Object[] parames = jp.getArgs();//获取目标方法体参数  
        for (int i = 0; i < parames.length; i++) {  
            System.out.println(parames[i]);  
        }  
        System.out.println(jp.getSignature().getName());  
        String className = jp.getTarget().getClass().toString();//获取目标类名  
        System.out.println("className:" + className);
        className = className.substring(className.indexOf("com"));  
        String signature = jp.getSignature().toString();//获取目标方法签名  
        System.out.println("signature:" + signature);
    }  
}

 4:在com.thc.tenantcenter包下及子包下方法上添加自己定义的注解

    @LogAnnotation(desc = "通过ID获取实体信息")
    @Override                                                                                              
    public AdminLog getAdminLogById(Integer id) {                                                    
        return adminLogMapper.getAdminLogById(id);                                                   
    }    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值