网站建设互联网营销营销推广,南阳网站制作价格,wordpress5.9文章编辑器,如何推广网站方法需求#xff1a; 自定义一个starter#xff0c;里面包含一个TimeLog注解和一个TimeLogAspect切面类#xff0c;用于统计接口耗时。要求在其它项目引入starter依赖后#xff0c;启动springboot项目时能进行自动装配。 步骤#xff1a; #xff08;1#xff09;引入pom依赖…需求 自定义一个starter里面包含一个TimeLog注解和一个TimeLogAspect切面类用于统计接口耗时。要求在其它项目引入starter依赖后启动springboot项目时能进行自动装配。 步骤 1引入pom依赖
dependencies!-- starter想要有自动装配功能就需要引入该依赖--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-autoconfigure/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-configuration-processor/artifactId/dependency!-- aop相关依赖 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-aop/artifactId/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/dependency/dependencies 2定义注解TimeLog
Target(ElementType.METHOD)
Retention(RetentionPolicy.RUNTIME)
public interface TimeLog {} Target注解作用“对象”这里声明注解作用在方法上。 Retention表示注解在运行时会被保留可以通过反射机制读取。 3定义切面类TimeLogAspect
Aspect
Component
public class TimeLogAspect {//切点所有标注了TimeLog注解的方法Pointcut(annotation(com.hammajang.annotation.TimeLog))public void timeConsume(){}Around(timeConsume())public Object doAround(ProceedingJoinPoint proceedingJoinPoint) {//开始时间long start System.currentTimeMillis();Object result null;try {//proceedingJoinPoint.proceed():真正的业务处理逻辑//result:业务的返回结果result proceedingJoinPoint.proceed();} catch (Throwable e) {e.printStackTrace();}//结束时间long end System.currentTimeMillis();System.out.println(proceedingJoinPoint.getSignature().getName() 接口执行总耗时 (end - start) ms);return result;}
} Aspect声明这是一个切面类。 Component声明这是一个bean在项目启动时需要加载到Spring容器中。 4定义TimeLogProperties
ConfigurationProperties(prefix hammajang)
Data
public class TimeLogProperties {/*** 日志开关*/private boolean enable;
} ConfigurationProperties将配置文件中的属性绑定到 JavaBeanTimeLogProperties中。注解声明了前缀是hammajang获取以hammajang为前缀的所有参数进行自动匹配赋值给类中对应的字段。 5定义TimeLogAutoConfiguration
Configuration
ComponentScan(basePackages com.hammajang)
ConditionalOnProperty(prefix hammajang,name enable,havingValue true)
EnableConfigurationProperties(value TimeLogProperties.class)
public class TimeLogAutoConfiguration {} Configuration声明这是一个配置类会被配置成bean装载到spring容器中。 ComponentScan扫描指定包路径可以指定多个将路径下符合要求的类对象配置成bean装载到spring容器中。 ConditionalOnproperty表示配置文件中存在一个以hammajang为前缀的属性属性名为enable当enable的值为true时havingValue true才会将TimeLogAutoConfiguration配置类装载到spring容器中。 EnableConfigurationProperties启用指定配置类value属性是一个class数组表示可以启用多个配置类。 6编译、打包starter 测试starter 1在pom文件中引入我们自定义的starter dependencygroupIdcom.hammajang/groupIdartifactIdmy-spring-boot-starter/artifactIdversion1.0-SNAPSHOT/version/dependency 2在controller层编写测试接口
RestController
RequestMapping(/order)
public class OrderController {GetMapping(/test)TimeLogpublic String test(){try {System.out.println(测试TimeLog注解...);//模拟业务处理Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}return success;}
} 3测试TimeLog注解是否生效 测试结果