Spring Boot 实现一个自定义的starter

Spring Boot 实现一个自定义的starter

目标

我们不需要在利用@Compont,@Bean等注解生成Bean。
利用Starter在项目启动时生成

功能

利用aop完成对接口时间的统计需要。

创建配置文件

Spring Boot在启动时会去找META-INF下的spring.factories配置文件。在项目启动时Spring会去根据这里的配置寻找需要装配的类。

`org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.example.config.LogsAutoConfig`

创建我们需要启动的类

这里我写了一个切面类,对接口的运行时间进行统计

@Aspect
public class LogsAspect {
    private final static Logger log = LoggerFactory.getLogger(LogsAspect.class);

    /**
     * 可重复使用的切点表达式
     */
    @Pointcut("@annotation(org.example.annotion.CountTime)")
    public void executeTiming(){}

    /**
     * 记录带有该注解的方法
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("executeTiming()")
    public Object logMethodTiming(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        long startTime = System.currentTimeMillis();
        Object returnValue = proceedingJoinPoint.proceed();
        long totalTime = System.currentTimeMillis() - startTime;
        log.info("程序执行时间 === > {}",totalTime);
        return returnValue;
    }
}

配套使用的注解

/**
 * 统计方法运行时间
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CountTime {
}

创建配置类

@Configuration
//@ConditionalOnClass(A.class) // 存在目标类时才会初始化
public class LogsAutoConfig {

    /**
     * 自动生成切面类
     * @return
     */
    @Bean
    @ConditionalOnMissingBean //当你的bean被注册之后,如果而注册相同类型的bean,就不会成功,它会保证你的bean只有一个,即你的实例只有一个
    public LogsAspect getBean() {
        return new LogsAspect();
    }
}

打包 使用

在代码编写完成后利用Maven打包工具进行打包后,我们可以像Spring官方提供的starter在其他的项目中引入。
在这里时我们只需要在我们需要统计时间的接口中加上注解就可以完成时间统计需求

@RestController
@RequestMapping(value = "/cache")
public class UserController {

    private final StudentService studentService;


    public UserController(StudentService userService) {
        this.studentService = userService;
    }
    
    @GetMapping("/count")
    @CountTime
    public Integer getStudentCount() {
       return studentService.getAllStudent().size();
    }
    
}

运行结果

2023-06-22 21:57:40.468  INFO 12028 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms
2023-06-22 21:57:40.547  INFO 12028 --- [nio-8080-exec-1] per.cache.demo.service.StudentService    : invoke getAllStudent method
2023-06-22 21:57:40.563  INFO 12028 --- [nio-8080-exec-1] org.example.aspect.LogsAspect            : 程序执行时间 === > 25
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值