经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
通用权限系统-Spring-Boot-Starter
来源:cnblogs  作者:JavaCoderPan  时间:2023/7/10 9:58:37  对本文有异议

Spring-Boot-Starter

自定义Starter

案例一:读取application.yml中的参数

1、创建

1、创建maven工程hello-spring-boot-starter
image
2、pom中添加依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>org.example</groupId>
  7. <artifactId>hello-spring-boot-starter</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <maven.compiler.source>8</maven.compiler.source>
  11. <maven.compiler.target>8</maven.compiler.target>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. </properties>
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>2.2.2.RELEASE</version>
  18. <relativePath/>
  19. </parent>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-autoconfigure</artifactId>
  28. </dependency>
  29. </dependencies>
  30. </project>

3、创建HelloProperties
配置属性类,用于封装配置文件中配置的参数信息

  1. package org.example.config;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. /**
  4. * TODO 配置属性类,用于封装配置文件中配置的参数信息
  5. *
  6. * @author ss_419
  7. * @version 1.0
  8. * @date 2023/7/8 13:55
  9. */
  10. @ConfigurationProperties(prefix = "hello")
  11. public class HelloProperties {
  12. private String name;
  13. private String address;
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public String getAddress() {
  21. return address;
  22. }
  23. public void setAddress(String address) {
  24. this.address = address;
  25. }
  26. @Override
  27. public String toString() {
  28. return "HelloProperties{" +
  29. "name='" + name + '\'' +
  30. ", address='" + address + '\'' +
  31. '}';
  32. }
  33. }

4、创建HelloService
这个类用于对读取到的参数进行一些业务上的操作

  1. package org.example.service;
  2. /**
  3. * TODO
  4. *
  5. * @author ss_419
  6. * @version 1.0
  7. * @date 2023/7/8 14:03
  8. */
  9. public class HelloService {
  10. private String name;
  11. private String address;
  12. public HelloService(String name, String address) {
  13. this.name = name;
  14. this.address = address;
  15. }
  16. public String sayHello(){
  17. return "你好!我的名字叫做"+name+",地址是" + address;
  18. }
  19. }

5、创建HelloServiceAutoConfiguration(用于自动配置HelloService对象)

  1. package org.example.config;
  2. import org.example.service.HelloService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  5. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. /**
  9. * TODO 自动配置类
  10. * 通过@Configuration + @Bean 实现自动创建对象
  11. *
  12. * @author ss_419
  13. * @version 1.0
  14. * @date 2023/7/8 14:06
  15. */
  16. @Configuration
  17. // 一定要加上这个注解,否则Spring找不到这个配置类
  18. @EnableConfigurationProperties(value = HelloProperties.class)
  19. public class HelloServiceAutoConfiguration {
  20. private HelloProperties helloProperties;
  21. // 通过构造方法注入配置属性对象HelloProperties
  22. public HelloServiceAutoConfiguration(HelloProperties helloProperties) {
  23. this.helloProperties = helloProperties;
  24. }
  25. // 实例化HelloService并载入Spring IOC 容器
  26. @Bean
  27. @ConditionalOnMissingBean// Spring中没有这个实例的时候再去创建
  28. public HelloService helloService(){
  29. return new HelloService(helloProperties.getName(), helloProperties.getAddress());
  30. }
  31. }

6、在resources目录下创建META-INF/spring.factories

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.config.HelloServiceAutoConfiguration

7、将工程打包到maven仓库中
image

2、使用

1、创建项目,导入自定义starter
image

2、创建application.yml配置文件
image
3、创建启动类

  1. package org.example;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. /**
  5. * TODO
  6. *
  7. * @author ss_419
  8. * @version 1.0
  9. * @date 2023/7/8 14:39
  10. */
  11. @SpringBootApplication
  12. public class HelloApplication {
  13. public static void main(String[] args) {
  14. SpringApplication.run(HelloApplication.class,args);
  15. }
  16. }

4、创建测试Controller

  1. package org.example.controller;
  2. import org.example.annotaion.MyLog;
  3. import org.example.service.HelloService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * TODO
  10. *
  11. * @author ss_419
  12. * @version 1.0
  13. * @date 2023/7/8 14:36
  14. */
  15. @RestController
  16. @RequestMapping("/hello")
  17. public class HelloController {
  18. @Autowired
  19. private HelloService helloService;
  20. @GetMapping("/sayHello")
  21. public String sayHello() {
  22. return helloService.sayHello();
  23. }
  24. }

5、测试
image

案例二:通过自动配置来创建一个拦截器对象,通过此拦截器对象来实现记录日志功能

1、创建

1、创建maven项目并且引入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>2.2.2.RELEASE</version>
  10. <relativePath/>
  11. </parent>
  12. <groupId>org.example</groupId>
  13. <artifactId>log-spring-boot-starter</artifactId>
  14. <version>1.0-SNAPSHOT</version>
  15. <properties>
  16. <maven.compiler.source>8</maven.compiler.source>
  17. <maven.compiler.target>8</maven.compiler.target>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-autoconfigure</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-web</artifactId>
  32. </dependency>
  33. </dependencies>
  34. </project>

2、创建MyLog注解

  1. package org.example.annotaion;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. @Target(ElementType.METHOD)
  7. @Retention(RetentionPolicy.RUNTIME)
  8. public @interface MyLog {
  9. /**
  10. * 方法描述
  11. * @return
  12. */
  13. String desc() default "";
  14. }

3、创建日志拦截器

  1. package org.example.interceptor;
  2. import org.example.annotaion.MyLog;
  3. import org.springframework.web.method.HandlerMethod;
  4. import org.springframework.web.servlet.ModelAndView;
  5. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.lang.reflect.Method;
  9. /**
  10. * TODO 自定义日志拦截器
  11. *
  12. * @author ss_419
  13. * @version 1.0
  14. * @date 2023/7/8 17:43
  15. */
  16. public class MyLogInterceptor extends HandlerInterceptorAdapter {
  17. private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();// 记录时间毫秒值
  18. /**
  19. * 执行之前
  20. * @param request
  21. * @param response
  22. * @param handler
  23. * @return
  24. * @throws Exception
  25. */
  26. @Override
  27. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  28. // 进行转换
  29. HandlerMethod handlerMethod = (HandlerMethod) handler;
  30. Method method = handlerMethod.getMethod();
  31. // 获取方法上的注解MyLog
  32. MyLog annotation = method.getAnnotation(MyLog.class);
  33. if(annotation != null){
  34. // 说明当前拦截到的方法上加入了MyLog注解
  35. long currentTimeMillis = System.currentTimeMillis();
  36. startTimeThreadLocal.set(currentTimeMillis);
  37. }
  38. return true;
  39. }
  40. /**
  41. * 执行之后
  42. * @param request
  43. * @param response
  44. * @param handler
  45. * @param modelAndView
  46. * @throws Exception
  47. */
  48. @Override
  49. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  50. HandlerMethod handlerMethod = (HandlerMethod) handler;
  51. Method method = handlerMethod.getMethod();
  52. // 获取方法上的注解MyLog
  53. MyLog annotation = method.getAnnotation(MyLog.class);
  54. if(annotation != null){
  55. // 说明当前拦截到的方法上加入了MyLog注解
  56. Long startTime = startTimeThreadLocal.get();
  57. long endTime = System.currentTimeMillis();
  58. long optTime = endTime - startTime;
  59. String requestUri = request.getRequestURI();
  60. String methodName = method.getDeclaringClass().getName() + "."+
  61. method.getName()+"()";
  62. String methodDesc = annotation.desc();
  63. System.out.println("请求uri:"+requestUri);
  64. System.out.println("请求方法名:"+methodName);
  65. System.out.println("方法描述:"+methodDesc);
  66. System.out.println("方法执行时间:"+optTime+"ms");
  67. }
  68. super.postHandle(request, response, handler, modelAndView);
  69. }
  70. }

4、创建自动装配对象

  1. package org.example.config;
  2. import org.example.interceptor.MyLogInterceptor;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  6. /**
  7. * TODO
  8. *
  9. * @author ss_419
  10. * @version 1.0
  11. * @date 2023/7/8 18:08
  12. */
  13. @Configuration
  14. public class MyLogAutoConfiguration implements WebMvcConfigurer {
  15. /**
  16. * 注册自定义日志拦截器
  17. * @param registry
  18. */
  19. @Override
  20. public void addInterceptors(InterceptorRegistry registry) {
  21. registry.addInterceptor(new MyLogInterceptor());
  22. }
  23. }

5、在resources下创建META-INF,在该文件夹下创建spring.factories
该配置文件用于扫描自动装配类

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.config.MyLogAutoConfiguration

2、使用

1、创建一个web项目,并且引入依赖,pom.xml如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>org.example</groupId>
  7. <artifactId>use-my-spring-boot-starter-demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.2.2.RELEASE</version>
  13. <relativePath/>
  14. </parent>
  15. <properties>
  16. <maven.compiler.source>8</maven.compiler.source>
  17. <maven.compiler.target>8</maven.compiler.target>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.example</groupId>
  23. <artifactId>log-spring-boot-starter</artifactId>
  24. <version>1.0-SNAPSHOT</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.example</groupId>
  32. <artifactId>hello-spring-boot-starter</artifactId>
  33. <version>1.0-SNAPSHOT</version>
  34. </dependency>
  35. </dependencies>
  36. </project>

2、创建测试Controller
在测试的方法上添加上自定义的MyLog注解,当该方法执行的时候就会在控制台输出对应信息

  1. package org.example.controller;
  2. import org.example.annotaion.MyLog;
  3. import org.example.service.HelloService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * TODO
  10. *
  11. * @author ss_419
  12. * @version 1.0
  13. * @date 2023/7/8 14:36
  14. */
  15. @RestController
  16. @RequestMapping("/hello")
  17. public class HelloController {
  18. @Autowired
  19. private HelloService helloService;
  20. @GetMapping("/sayHello")
  21. @MyLog(desc = "sayHello方法")
  22. public String sayHello() {
  23. return helloService.sayHello();
  24. }
  25. }

3、测试
image

到这里,对于自定义starter的案例就结束了。

原文链接:https://www.cnblogs.com/atwood-pan/p/17537825.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号