欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > springboot自定义starter

springboot自定义starter

2024/10/24 23:30:26 来源:https://blog.csdn.net/weixin_43732943/article/details/141039646  浏览:    关键词:springboot自定义starter

案例1:自定义starter中配置用户信息、接口访问。使用starter时在yml文件配置用户信息

1,创建自定义starter
1.1,创建starter工程xxx-spring-boot-starter并配置pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/></parent><groupId>cn.xxx</groupId><artifactId>xxx-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><!--   lombok   --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.6</version></dependency></dependencies>
</project>

1.2,创建配置属性类XXXProperties

/**读取配置文件转换为bean* */
@Data
@ConfigurationProperties(prefix = "xxx")
public class XXXProperties {private String name;private String address;
}

1.3,创建自动配置类XXXServiceAutoConfiguration

@Configuration
//启用配置属性类
@EnableConfigurationProperties(TQProperties.class)
public class TianQingAutoConfiguration {private TQProperties tqProperties;//通过构造方法注入配置属性对象HelloPropertiespublic TianQingAutoConfiguration(TQProperties tqProperties) {this.tqProperties = tqProperties;}//实例化UserInfo并载入Spring IoC容器@Bean@ConditionalOnMissingBeanpublic UserInfo userInfo(){return new UserInfo (tqProperties.getName(),tqProperties.getAddress());}
}

1.4,在resources目录下创建META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meteorological.config.XXXAutoConfiguration

1.5,创建UserInfo

@Data
public class UserInfo {private String name;private String address;public UserInfo (String name, String address) {this.name = name;this.address = address;}
}

1.6,创建server类

@Service
public class DMService {@Autowiredprivate UserInfo userInfo;public String getInfo(){return userInfo.getName()+" address: "+userInfo.getAddress();}
}

2,使用starter
2.1,创建maven工程并配置pom.xml文件,加入自定义starter依赖

//省略
<dependencies><!--导入自定义starter--><dependency><groupId>cn.tianqing</groupId><artifactId>tianqing-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version></dependency>
</dependencies>

2.2,修改application.yml文件

xxx:name: xiaomingaddress: beijing

2.3,调用自定义starter中服务

@Component
public class CustomStarterTest {//注入自定义starter中的server类@AutowiredDMService dmService;@PostConstructpublic void task1() {System.out.println(dmService.getInfo());}
}

案例2:自定义拦截器记录服务执行时间

1.1,自定义starter的pom.xml文件中添加web依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><optional>true</optional>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId>
</dependency>

1.2,自定义MyLog注解

@Target(ElementType.METHOD)//仅在方法上使用
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {/*** 方法描述*/String desc() default "";
}

1.3,自定义日志拦截器MyLogInterceptor

/*** 日志拦截器*/
public class MyLogInterceptor extends HandlerInterceptorAdapter {private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {HandlerMethod handlerMethod = (HandlerMethod)handler;//获得被拦截的方法对象Method method = handlerMethod.getMethod();//获得方法上的注解MyLog myLog = method.getAnnotation(MyLog.class);if(myLog != null){//方法上加了MyLog注解,需要进行日志记录long startTime = System.currentTimeMillis();startTimeThreadLocal.set(startTime);}return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {HandlerMethod handlerMethod = (HandlerMethod)handler;//获得被拦截的方法对象Method method = handlerMethod.getMethod();//获得方法上的注解MyLog myLog = method.getAnnotation(MyLog.class);if(myLog != null){//方法上加了MyLog注解,需要进行日志记录long endTime = System.currentTimeMillis();//ThreadLocal中获取开始时间Long startTime = startTimeThreadLocal.get();long optTime = endTime - startTime;System.out.println("方法执行时间:" + optTime + "ms");String requestUri = request.getRequestURI();//类名+方法名String methodName = method.getDeclaringClass().getName() + "." + method.getName();String methodDesc = myLog.desc();System.out.println("请求uri:" + requestUri);System.out.println("请求方法名:" + methodName);System.out.println("方法描述:" + methodDesc);}}
}

1.4,创建自动配置类MyLogAutoConfiguration,用于自动配置拦截器、参数解析器等web组件

/*** 配置类,用于自动配置拦截器、参数解析器等web组件*/
@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer{//注册自定义日志拦截器public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyLogInterceptor());}
}

1.5,在spring.factories中追加MyLogAutoConfiguration配置

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meteorological.config.XXXAutoConfiguration,\
cn.meteorological.config.MyLogAutoConfiguration

2,使用自定义starter
2.1,Controller方法上加入@MyLog注解

@RestController
@RequestMapping("/hello")
public class HelloController {@Autowiredprivate HelloService helloService;//日志记录注解@MyLog(desc = "sayHello方法")@GetMapping("/say")public String sayHello(){return helloService.sayHello();}
}

2.2,访问地址:http://localhost:8080/hello/say,查看控制台输出:

请求uri:/hello/say
请求方法名:cn.meteorological.controller.HelloController.sayHello
方法描述:sayHello方法
方法执行时间:36ms

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com