Spring boot 实现注解方式日志记录starter

1、首先创建一个新的 Maven 项目

       引入依赖如下:

     <---- 自动配置--->
      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
     <---- AOP starter--->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency> 

2、定义注解

package com.ld.demo.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogAnnotation  {

}

3、定义AOP,拦截注解了@LogAnnotation的方法


@Aspect 
public class LogAnnotationAspect {

    @Around("@annotation(logAnnotation)")
    public Object logMethodExecution(ProceedingJoinPoint joinPoint, LogAnnotation logAannotation) throws Throwable {
        MethodSignature methodSign = (MethodSignature) joinPoint.getSignature();
        String methodName = methodSign.getDeclaringTypeName() + "." + methodSign.getName();
        Object[] methodArgs = joinPoint.getArgs();
        System.out.println(methodName);
        System.out.println( Arrays.toString(methodArgs));
        return joinPoint.proceed();
    }
}

4、创建自动配置类

package com.ld.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import com.ld.demo.aspect.LogAnnotationAspect;

@Configuration
@EnableAspectJAutoProxy
public class LogStarterAutoConfiguration {

    @Bean
    LogAnnotationAspect logAnnotationAspect() {
        return new LogAnnotationAspect();
    }
}

5、配置 META-INF/spring.factories

 resources下新建文件夹和文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.ld.demo.config.LogStarterAutoConfiguration

  注意:以上是spring boot 2.x版本的方式,3.x是META-INF/spring/下面创建文件org.springframework.boot.autoconfigure.AutoConfiguration.imports,文件内容是: 

com.ld.demo.config.LogStarterAutoConfiguration

6、如何使用 

   工程打包,在其它工程引入对应的依赖,根据实际坐标引入

		<dependency>
			<groupId>XXXX</groupId>
			<artifactId>XXXXXX</artifactId>
		</dependency>	

Controller请求方法上加注解

package com.ld.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ld.demo.annotation.LogAnnotation;
@RestController
@RequestMapping("/hello")
public class HelloController {	
	@LogAnnotation
    @GetMapping("/world")
	public String world() {
		return "test";
	}
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值