赞
踩
对于企业中的项目绝大多数都需要进行用户权限管理、认证、鉴权、加密、解密、XSS防跨站攻击等。这些功能整体实现思路基本一致,但是绝大部分项目都需要实现一次,这无形中就形成了巨大的资源浪费。本项目就是针对这个问题,提供了一套通用的权限解决方案——品达通用权限系统。
品达通用权限系统基于SpringCloud(Hoxton.SR1)+SpringBoot(2.2.2.RELEASE)的微服务框架,具备通用的用户管理、资源权限管理、网关统一鉴权、XSS防跨站攻击等多个模块、支持多业务系统并行开发、可作为后端服务的开发脚手架。核心技术采用SpringBoot、Zuul、Nacos、Fegin、Ribbon、Hystrix、JWT Token、Mybatis Plus等主要框架和中间件。
本项目具有两个主要功能特性:


我们知道Spring Boot大大简化了项目初始搭建以及开发过程,而这些都是通过Spring Boot提供的starter来完成的。品达通用权限系统就是基于Spring Boot进行开发,而且一些基础模块其本质就是starter,所以我们需要对Spring Boot的starter有一个全面深入的了解,这是我们开发品达通用权限系统的必备知识。
Spring Boot在配置上相比Spring要简单许多,其核心在于spring-boot-starter,在使用Spring Boot来搭建一个项目时,只需要引入官方提供的starter,就可以直接使用,免去了各种配置。starter简单来讲就是引入了一些相关依赖和一些初始化的配置。
spring-boot-starter-xxxspring-boot-starter-webxxx-spring-boot-startermybatis-spring-boot-starterSpring Boot之所以能够帮我们简化项目的搭建和开发过程,主要是基于它提供的起步依赖和自动配置。
起步依赖,其实就是将具备某种功能的坐标打包到一起,可以简化依赖导入的过程。例如,我们导入spring-boot-starter-web这个starter,则和web开发相关的jar包都一起导入到项目中了。如下图所示:

自动配置,就是无须手动配置xml,自动配置并管理bean,可以简化开发过程。那么Spring Boot是如何完成自动配置的呢?
自动配置涉及到如下几个关键步骤:
我们可以通过一个实际的例子mybatis-spring-boot-starter来说明自动配置的实现过程。
当我们在项目中导入mybatis-spring-boot-starter这个jar后,可以看到它包括了很多相关的jar包,如下图:

其实在mybatis-spring-boot-autoconfigure这个jar包中有如下一个MybatisAutoConfiguration自动配置类:

打开这个类,截取的关键代码如下:


@Configuration 和 @Bean 这两个注解一起使用就可以创建一个基于Java代码的配置类,可以用来代替传统的xml配置文件。
@Configuration 注解的类可以看作是能够生产让Spring IOC容器管理的bean实例工厂。
@Bean 注解的方法返回的对象可以被注册到spring容器中。
所以上面的MybatisAutoConfiguration这个类,自动帮我们生成了SqlSessionFactory和SqlSessionTemplate这些Mybatis的重要实例并交给spring容器管理,从而完成bean的自动注册。
从MybatisAutoConfiguration这个类中使用的注解可以看出,要完成自动配置是有依赖条件的。

所以要完成Mybatis的自动配置,需要在类路径中存在SqlSessionFactory.class、SqlSessionFactoryBean.class这两个类,同时需要存在DataSource这个bean且这个bean完成自动注册。
这些注解是spring boot特有的,常见的条件依赖注解有:
| 注解 | 功能说明 |
|---|---|
| @ConditionalOnBean | 仅在当前上下文中存在某个bean时,才会实例化这个Bean |
| @ConditionalOnClass | 某个class位于类路径上,才会实例化这个Bean |
| @ConditionalOnExpression | 当表达式为true的时候,才会实例化这个Bean |
| @ConditionalOnMissingBean | 仅在当前上下文中不存在某个bean时,才会实例化这个Bean |
| @ConditionalOnMissingClass | 某个class在类路径上不存在的时候,才会实例化这个Bean |
| @ConditionalOnNotWebApplication | 不是web应用时才会实例化这个Bean |
| @AutoConfigureAfter | 在某个bean完成自动配置后实例化这个bean |
| @AutoConfigureBefore | 在某个bean完成自动配置前实例化这个bean |
要完成mybatis的自动配置,需要我们在配置文件中提供数据源相关的配置参数,例如数据库驱动、连接url、数据库用户名、密码等。那么spring boot是如何读取yml或者properties配置文件的属性来创建数据源对象?
在我们导入mybatis-spring-boot-starter这个jar包后会传递过来一个spring-boot-autoconfigure包,在这个包中有一个自动配置类DataSourceAutoConfiguration,如下所示:

我们可以看到这个类上加入了EnableConfigurationProperties这个注解,继续跟踪源码到DataSourceProperties这个类,如下:

可以看到这个类上加入了ConfigurationProperties注解,这个注解的作用就是把yml或者properties配置文件中的配置参数信息封装到ConfigurationProperties注解标注的bean(即DataSourceProperties)的相应属性上。
@EnableConfigurationProperties注解的作用是使@ConfigurationProperties注解生效。
spring boot默认扫描启动类所在的包下的主类与子类的所有组件,但并没有包括依赖包中的类,那么依赖包中的bean是如何被发现和加载的?
我们需要从spring boot项目的启动类开发跟踪,在启动类上我们一般会加入
SpringBootApplication注解,此注解的源码如下:

重点介绍如下三个注解:
SpringBootConfiguration:作用就相当于Configuration注解,被注解的类将成为一个bean配置类
ComponentScan:作用就是自动扫描并加载符合条件的组件,最终将这些bean加载到spring容器中
EnableAutoConfiguration :这个注解很重要,借助@Import的支持,收集和注册依赖包中相关的bean定义
继续跟踪EnableAutoConfiguration注解源码:

@EnableAutoConfiguration注解引入了@Import这个注解。
Import:导入需要自动配置的组件,此处为EnableAutoConfigurationImportSelector这个类
EnableAutoConfigurationImportSelector类源码如下:

EnableAutoConfigurationImportSelector继承了AutoConfigurationImportSelector类,继续跟踪AutoConfigurationImportSelector类源码:

AutoConfigurationImportSelector类的getCandidateConfigurations方法中的调用了SpringFactoriesLoader类的loadFactoryNames方法,继续跟踪源码:

SpringFactoriesLoader的loadFactoryNames静态方法可以从所有的jar包中读取META-INF/spring.factories文件,而自动配置的类就在这个文件中进行配置:

spring.factories文件内容如下:

这样Spring Boot就可以加载到MybatisAutoConfiguration这个配置类了。
在Spring Boot应用中要让一个普通类交给Spring容器管理,通常有以下方法:
@Configuration与@Bean 注解@Controller、 @Service 、@Repository、 @Component 注解标注该类并且启用@ComponentScan自动扫描@Import 方法其中Spring Boot实现自动配置使用的是@Import注解这种方式,AutoConfigurationImportSelector类的selectImports方法返回一组从META-INF/spring.factories文件中读取的bean的全类名,这样Spring Boot就可以加载到这些Bean并完成实例的创建工作。
我们可以将自动配置的关键几步以及相应的注解总结如下:
@Configuration与@Bean:基于Java代码的bean配置@Conditional:设置自动配置条件依赖@EnableConfigurationProperties与@ConfigurationProperties:读取配置文件转换为bean@EnableAutoConfiguration与@Import:实现bean发现与加载本小节我们通过自定义两个starter来加强starter的理解和应用。
第一步:创建starter工程hello-spring-boot-starter并配置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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> </parent> <groupId>com.xbmu</groupId> <artifactId>hello-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> </dependencies> </project>
第二步:创建配置属性类 HelloProperties
package com.xbmu.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * 读取配置文件转换为bean */ @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 + '\'' + '}'; } }
第三步:创建服务类HelloService
package com.xbmu.service;
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;
}
}
第四步:创建自动配置类HelloServiceAutoConfiguration
package com.xbmu.config; import com.xbmu.service.HelloService; 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; /** * 配置类,基于Java代码的bean配置 */ @Configuration @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { private HelloProperties helloProperties; // 通过构造方法注入配置属性对象 HelloProperties public HelloServiceAutoConfiguration(HelloProperties helloProperties) { this.helloProperties = helloProperties; } // 实例化HelloService并载人Spring IOC容器 @Bean @ConditionalOnMissingBean public HelloService helloService(){ return new HelloService(helloProperties.getName(),helloProperties.getAddress()); } }
第五步:在 resources目录下创建 META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xbmu.config.HelloServiceAutoConfiguration

至此starter已经开发完成了,可以将当前starter安装到本地maven仓库供其他应用来使用。


第一步:创建maven工程myapp并配置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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> </parent> <groupId>com.xbmu</groupId> <artifactId>myapp</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 导入自定义的starter --> <dependency> <groupId>com.xbmu</groupId> <artifactId>hello-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> </project>
第二步:创建 application.yml文件
server:
port: 8080
hello:
name: bitaotao
address: xian
第三步:创建HelloController
package com.xbmu.contoller; import com.xbmu.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; @RestController @RequestMapping("/hello") public class HelloController { // HelloService在我们自定义的starter中已经完成了自动配置,所以此处可以直接注入 @Autowired private HelloService helloService; @GetMapping("/say") public String sayHello(){ return helloService.sayHello(); } }
第四步:创建启动类HelloApplication
package com.xbmu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class,args);
}
}
执行启动类main方法,访问地址 http://localhost:8080/hello/say

在前面的案例一中我们通过定义starter,自动配置了一个HelloService实例。本案例我们需要通过自动配置来创建一个拦截器对象,通过此拦截器对象来实现记录日志功能。
我们可以在案例一的基础上继续开发案例二。
第一步:在hello-spring-boot-starter的pom.xml文件中追加如下maven坐标
<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>
第二步:自定义MyLog注解
package com.xbmu.log;
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 {
/**
* 方法描述
*/
String desc() default "";
}
第三步:自定义日志拦截器MyLogInterceptor
package com.xbmu.log; 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; /** * 日志拦截器 */ 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(); Long startTime = startTimeThreadLocal.get(); long optTime = endTime - startTime; 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); System.out.println("方法执行时间:" + optTime + "ms"); } } }
第四步:创建自动配置类MyLogAutoConfiguration,用于自动配置拦截器、参数解析器等web组件
package com.xbmu.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 配置类,用于自动配置拦截器、参数解析器等web组件 */ @Configuration public class MyLogAutoConfiguration implements WebMvcConfigurer{ //注册自定义日志拦截器 public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyLogInterceptor()); } }
第五步:在spring.factories中追加MyLogAutoConfiguration配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xbmu.config.HelloServiceAutoConfiguration,\
com.xbmu.config.MyLogAutoConfiguration

注意:我们在hello-spring-boot-starter中追加了新的内容,需要重新打包安装到maven仓库。
在myapp工程的Controller方法上加入@MyLog注解

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

lombok是一个开源的代码生成库,能以简单的注解形式来简化Java类中的大量样板代码,提高开发人员的开发效率。例如开发中经常需要写的JavaBean,都需要花时间去添加相应的getter/setter,也许还要去写构造器、equals等方法,而且需要维护,当属性多时会出现大量的getter/setter方法,这些显得很冗长也没有太多技术含量。
lombok能通过注解的方式,在编译时自动为属性生成构造器、getter/setter、equals、hashcode、toString方法,使代码看起来更简洁。
lombok对应的maven坐标:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
要使用lombok需要在IDE中安装对应的lombok插件。本课程使用的开发工具为IntelliJ IDEA,安装插件过程如下:
| 注解 | 说明 |
|---|---|
| @Setter | 注解在类或属性,注解在类时为所有属性生成setter方法,注解在属性上时只为该属性生成setter方法 |
| @Getter | 使用方法同@Setter,区别在于生成的是getter方法 |
| @ToString | 注解在类,添加toString方法 |
| @EqualsAndHashCode | 注解在类,生成hashCode和equals方法 |
| @NoArgsConstructor | 注解在类,生成无参的构造方法 |
| @RequiredArgsConstructor | 注解在类,为类中需要特殊处理的属性生成构造方法,比如final和被@NonNull注解的属性 |
| @AllArgsConstructor | 注解在类,生成包含类中所有属性的构造方法 |
| @Data | 注解在类,生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法 |
| @Slf4j | 注解在类,生成log变量,用于记录日志 |
| @Builder | 将类转变为建造者模式 |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。