首页 > 其他分享 >通用权限系统-Spring-Boot-Starter

通用权限系统-Spring-Boot-Starter

时间:2023-07-08 20:45:00浏览次数:35  
标签:Spring boot Boot springframework annotation org import public Starter

Spring-Boot-Starter

自定义Starter

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

1、创建

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

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>hello-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/>
    </parent>
    <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>
    </dependencies>
</project>

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

package org.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * TODO 配置属性类,用于封装配置文件中配置的参数信息
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/7/8 13:55
 */
@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
    private String name;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "HelloProperties{" +
                "name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

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

package org.example.service;

/**
 * TODO
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/7/8 14:03
 */
public class HelloService {
    private String name;
    private String address;

    public HelloService(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String sayHello(){
        return "你好!我的名字叫做"+name+",地址是" + address;
    }
}

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

package org.example.config;

import org.example.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * TODO 自动配置类
 * 通过@Configuration + @Bean 实现自动创建对象
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/7/8 14:06
 */
@Configuration
// 一定要加上这个注解,否则Spring找不到这个配置类
@EnableConfigurationProperties(value = HelloProperties.class)
public class HelloServiceAutoConfiguration {


    private HelloProperties helloProperties;

    // 通过构造方法注入配置属性对象HelloProperties
    public HelloServiceAutoConfiguration(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }
    // 实例化HelloService并载入Spring IOC 容器
    @Bean
    @ConditionalOnMissingBean// Spring中没有这个实例的时候再去创建
    public HelloService helloService(){
        return new HelloService(helloProperties.getName(), helloProperties.getAddress());
    }
}

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

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

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

2、使用

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

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

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * TODO
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/7/8 14:39
 */
@SpringBootApplication
public class HelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class,args);
    }
}

4、创建测试Controller

package org.example.controller;

import org.example.annotaion.MyLog;
import org.example.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/7/8 14:36
 */
@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private HelloService helloService;

    @GetMapping("/sayHello")
    
    public String sayHello() {
     return helloService.sayHello();
    }
}

5、测试
image

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

1、创建

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

<?xml version="1.0" encoding="UTF-8"?>
<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 http://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>org.example</groupId>
    <artifactId>log-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

2、创建MyLog注解

package org.example.annotaion;

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

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

3、创建日志拦截器

package org.example.interceptor;

import org.example.annotaion.MyLog;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * TODO 自定义日志拦截器
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/7/8 17:43
 */
public class MyLogInterceptor extends HandlerInterceptorAdapter {
    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();// 记录时间毫秒值

    /**
     * 执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 进行转换
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 获取方法上的注解MyLog
        MyLog annotation = method.getAnnotation(MyLog.class);
        if(annotation != null){
            // 说明当前拦截到的方法上加入了MyLog注解
            long currentTimeMillis = System.currentTimeMillis();
            startTimeThreadLocal.set(currentTimeMillis);
        }
        return true;
    }

    /**
     * 执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 获取方法上的注解MyLog
        MyLog annotation = method.getAnnotation(MyLog.class);
        if(annotation != null){
            // 说明当前拦截到的方法上加入了MyLog注解
            Long startTime = startTimeThreadLocal.get();
            long endTime = System.currentTimeMillis();
            long optTime =  endTime - startTime;

            String requestUri = request.getRequestURI();
            String methodName = method.getDeclaringClass().getName() + "."+
                                method.getName()+"()";
            String methodDesc = annotation.desc();

            System.out.println("请求uri:"+requestUri);
            System.out.println("请求方法名:"+methodName);
            System.out.println("方法描述:"+methodDesc);
            System.out.println("方法执行时间:"+optTime+"ms");

        }
        super.postHandle(request, response, handler, modelAndView);
    }
}

4、创建自动装配对象

package org.example.config;

import org.example.interceptor.MyLogInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * TODO
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/7/8 18:08
 */
@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer {
    /**
     * 注册自定义日志拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyLogInterceptor());
    }
}

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

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

2、使用

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

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>use-my-spring-boot-starter-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/>
    </parent>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>log-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>hello-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

</project>

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

package org.example.controller;

import org.example.annotaion.MyLog;
import org.example.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/7/8 14:36
 */
@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private HelloService helloService;

    @GetMapping("/sayHello")
    @MyLog(desc = "sayHello方法")
    public String sayHello() {
     return helloService.sayHello();
    }
}

3、测试
image

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

标签:Spring,boot,Boot,springframework,annotation,org,import,public,Starter
From: https://www.cnblogs.com/atwood-pan/p/17537825.html

相关文章

  • Web开发|SpringBoot-Bean
    起因:经常在Config文件里看见Bean的存在,所以开始探究Bean的概念还使用方法。原文来自:https://gustavopeiretti.com/spring-boot-bean-annotation/#:~:text=What%20is%20%40Configuration%20in%20Spring,other%20parts%20of%20the%20application. 在SpringBoot中,@Bean是一个方......
  • spring-boot集成mybatis-plus
    spring-boot集成mybatis-plus目录spring-boot集成mybatis-plus依赖配置application.properties文件启动类添加@Mapper注解编码实体类Mapper类Service类测试@Test测试测试结果依赖 <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter<......
  • Spring中的Controller和Service是线程安全的吗?我有点懵
    结论:不是线程安全的Spring容器中的Bean是否线程安全,容器本身并没有提供Bean的线程安全策略,因此可以说Spring容器中的Bean本身不具备线程安全的特性,但是具体还是要结合具体scope的Bean去研究。Spring的bean作用域(scope)类型singleton:单例,默认作用域。prototype:原型,每次创......
  • spring
    SpringSpring简介Spring是一个开源的设计层面框架,它解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应特点:Spring是一个开源免费的框架,容器;Spring是一个轻量级的框架,非入侵式的;控制反转IoC,面向切面编程AOP;对事务的支持,对框架的支持......
  • Spring整合web环境(Servlet)
    前提:Spring系列坐标版本统一,否则会出现版本问题发布之前先进行打包,可以暴露一些代码配置上的问题,避免出现找不到资源的问题1.创建Servlet @WebServlet注解用于配置Servlet,相当于web.xml中的以下代码<servlet><servlet-name>AccountServlet</servlet-name><servlet-c......
  • 如何实现获取spring boot线程池中的所有线程的具体操作步骤
    获取SpringBoot线程池中的所有线程作为一名经验丰富的开发者,我将向你介绍如何获取SpringBoot线程池中的所有线程。这将帮助你更好地了解线程池的工作原理,并能在开发过程中更好地监控和管理线程。整体流程下面是整个过程的步骤概览:步骤描述1获取SpringBoot应用上下......
  • SpringBoot 项目不加载 application.properties 配置文件
    yml或者properties文件没有被扫描到,需要在pom文件中<build></build>添加如下内容来保证文件都能正常被扫描到并且加载成功。<resources><resource><directory>src/main/java</directory><includes><include>**/*.yml</include......
  • 公司刚来的京东架构师:看完我写的spring笔记,甩给了我一份文档
    pring是分层的full-stack(全栈)轻量级开源框架,以IoC和AOP为内核,提供了展现层SpringMVC和业务层事务管理等众多的企业级应⽤技术,还能整合开源世界众多著名的第三⽅框架和类库,已经成为使⽤最多的JavaEE企业应⽤开源框架。  本文目录:Spring概述核心思想手写......
  • 【企业项目实战】Spring Boot 启动时加载指定方法
    ......
  • Java技术分享:SpringBoot+mysql+...
    放个效果图: 准备项目首先在MySql控制台输入一下sql语句创建student数据库和student。createdatabsestudent;usestudent;CREATETABLE`student`(`stu_id`bigint(20)NOTNULL,`stu_name`varchar(45)DEFAULTNULL,`stu_sex`varchar(6)DEFAULTNUL......