项目介绍和Spring Boot starter 使用
使用)
项目概述
项目介绍
对于企业中的项目大多数都需要进行用户权限管理、认证、鉴权、加密、解密、XSS防跨站攻击等。这些功能实现思路基本一致,但是大部分项目都需要实现一次,这无形中就形成了巨大的资源浪费。本项目就是针对这个问题,提供了一套通用的权限解决方案----品达通用权限系统
品达通用权限系统基于SpringCloud(Hoxton.SR1)+SpringBoot(2.2.2.RELEASE)的微服务框架,具备通用的用户管理、资源权限管理、网关统一鉴权、XSS防跨站攻击等多个模块,支持多业务系统并行开发,支持多服务开发,可以作为后端服务的开发脚手架。核心技术采用SpringBoot、Zuul、Nacos、Fegin、Ribbon、JWT token、Mybatis Plus等
本项目具有两个主要的功能特性:
- 用户权限管理
具有用户、部门、岗位、角色、菜单管理,并通过网关进行统一的权限认证- 微服务开发框架
本项目同时也是一个微服务开发框架,集成了基础的公共组件、包括数据库、缓存、日志、表单验证、对象转换、仿注入和接口文档管理等工具
业务架构
技术架构
技术要求
- JDK1.8
- Maven3.3
- Mysql5.6+
- Redis4.0+
- Nacos1.1.4
- Node11.3+(集成npm)
Spring Boot starter
我们知道SpringBoot大大简化了项目初始化搭建以及开发的过程,而这些都是通过SpringBoot提供的stater来完成的。品达通用权限系统就是基于SpringBoot进行开发,而且一些基础模块其本质就是stater。
starter介绍
SpringBoot再配置上相比Spring要简单许多,其核心在于Spring-boot-stater,在使用Spring boot来搭建一个项目时,只需要引入官方提供的starter,就可以直接使用,免去了各种配置。starter简单来讲就是引入了一些相关依赖和一些初始化配置
Spring官方提供了很多stater,第三方也可以定义为stater。为了加以区分,stater从名称上进行了如下规范:
- Spring官方提供的stater名称为:spring-boot-stater-XXX。例如:spring-boot-stater-web
第三方提供的stater名称为:xxx-spring-boot-stater。例如mybatis-spring-boot-stater
stater原理
SpringBoot之所以能够帮助我们简化项目搭建和开发过程,主要是基于他提供的起步依赖和自动配置
起步依赖
起步依赖,其实就是将具有某种功能的坐标打包到一起,简化依赖导入过程
例如 spring-boot-stater-web
自动配置
自动配置,就是无须手动配置xml,自动配置并管理bean,可以简化开发过程。那么Spring boot是如何完成自动配置的呢?
自动配置涉及如下几个关键步骤:
以mybatis-spring-boot-stater为例:
基于java代码的Bean的配置
当我们在项目中导入了mybatis-spring-boot-stater这个jar后,可以看到它包括了很多相关的jar包,如下图
其中在mybatis-spring-boot-autoconfig这个jar包中有一个MybatisAutoConfiguration自动配置类
@Configration和@Bean这两个注解一起使用就可以创建一个基于java代码的配置类,可以用来替换传统的xml配置文件
@Configuration注解的类可以看作是能生产让Spring IOC容器管理Bean实例的工厂
@Bean注解的方法返回的对象就可以被注册到Spring容器中
所以上面MybatisAutoConfiguration这个类,自动帮我们生成了SqlSessionFactory和SqlSessionTemplate这些Mybatis的重要的实例并交由Spring容器管理,从而完成Bean的自动注册
自动配置条件依赖
从MybatisAutoConfiguration这个类中使用的注解可以看出,要完成自动配置是有依赖条件的
所以要完成Mybatis的自动配置,需要在类路径中存在SqlSessionFactory.class、SqlSessionFactoryBean.class这两个类,同时需要存在DataSource这个bean且这个bean 完成自动注册
这些注解是Springboot特有的,常见的条件依赖注解有:
- @ConditionOnBean 仅在当前上下文中存在某个bean时,才会实例化这个bean
- @ConditionalOnClass 某个class位于类路径上,才会实例化这个bean
- @ConditionOnExpression 当表达式为true的时候,才会实例化这个bean
- @ConditionOnMissingBean 仅在当前上下文中不存在某个bean时,才会实例化这个bean
- @ConditionOnMissingClass 某个class在类路径上不存在的时候,才会实例化这个bean
- @ConditionOnNotWebApplication 不是web应用时才会实例化这个bean
- @AutoConfigAfter 在某个bean完成自动配置后实例化这个bean
- @AutoConfigurationBefore 在某个bean完成自动配置前实例化这个bean
Bean 的参数获取
要完成mybatis的自动配置,需要我们在配置文件中提供数据源相关的配置参数,例如数据库驱动、连接URL、数据库用户名、密码等。那么springboot是如何读取yml或者properties配置文件的属性来创建数据源对象的?
在我们导入mybatis-spring-boot-stater这个jar包后会传递来一个spring-boot-autoconfiguration包,在这个包中有一个自动配置类DataSourceAutoConfiguration,如下所示:
我们可以看到这个类上加入了EnableConfigurationProperties这个注解,继续跟踪源码到DataSourceProperties这个类,如下:
可以看到这个类上加入了 ConfigurationProperties 注解,这个注解的作用就是把yml或者properties配置文件中的配置参数信息封装到ConfigurationProperties注解标注的bean(即DataSourceProperties)的相应属性上
@EnableConfigurationProperties主机的作用是 @ConfigurationProperties 注解生效
Bean的发现
springboot默认扫描启动类所在的包下的主类与子类的所有组件,但并没有包括依赖包中的类,那么依赖包中的bean是如何发现和加载的?
我们需要从Spring boot项目的启动类开始跟踪,在启动类上我们一般会加入SpringBootApplication注解,此注解的源码如下:
追踪源码,发现
spring.factories文件内容如下:
这样Spring boot就可以加载到MybatisAutoConfiguration 这个配置类了
Bean 的加载
在Spring Boot应用中要让一个普通类交给Spring容器管理,通常有以下方法:
- 使用@Configuration与@Bean注解
- 使用@Controller、@Service、@Repository、@Component注解标注该类并且启用@CompontScan自动扫描
- 使用@Import方法
其中Spring Boot实现自动配置使用的是@Import注解这种方式,AutoConfigurationSelector类的selectImports方法返回一组从META-INF/spring.factories文件中读取的bean的全类名,这样Spring Boot就可以加载到这些Bean并完成实例的创建工作
自动配置总结
自动配置关键步骤
- @Configuration与@Bean:基于java代码的bean配置
- @Conditional设置自动配置条件依赖
- @EnableConfigurationProperties与@ConfigurationProperties:读取配置文件转换成bean
- @EnableAutoConfiguration与@Import:实现bean发现与bean加载
自定义stater
案例一
- 创建starter(maven)工程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 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/> <!-- lookup parent from repository -->
</parent>
<groupId>it.cast</groupId>
<artifactId>hello-spring-boot-stater</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hello-spring-boot-stater</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</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>
</dependencies>
</project>
- 创建配置属性类HelloProperties
/**
* 读取配置文件 转换成 Bean 对象
*/
@ConfigurationProperties("hello")
public class HelloProperties {
private String name;
private String address;
// 注意 Spring默认使用空参构造 创建对象
public HelloProperties(){}
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;
}
}
- 创建服务类
/**
* 服务类
*/
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;
}
}
- 创建自动配置类
/**
* 配置类 基于java代码的bean配置
*/
@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
private HelloProperties helloProperties;
// 通过构造方法注入配置属性对象
public HelloServiceAutoConfiguration(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
@Bean
@ConditionalOnMissingBean
public HelloService helloService(){
return new HelloService(helloProperties.getName(), helloProperties.getAddress());
}
}
- 在resources目录下创建META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
cn.itcast.config.HelloServiceAutofiguration
至此starter已经开发完成了,可以将当前starter安装到本地maven(使用maven install)仓库供其他应用来使用
使用
- 创建工程
- pom.xml
<dependencies>
<dependency>
<groupId>it.cast</groupId>
<artifactId>hello-spring-boot-stater</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Idea可能会检测不到,update
- application.yml
server:
port: 8888
hello:
name: lisi
address: wangzhuang
- controller
@RestController
@RequestMapping("/my")
public class MyController {
@Autowired
private HelloService helloService;
@GetMapping("say")
public String say(){
return helloService.sayHello();
}
}
访问:
案例二
自动配置创建一个拦截器对象,通过此拦截器对象来实现记录日志功能
在案例一的基础上实现案例二
- 开发starter,在pom.xml文件追加如下maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
- 自定义MyLog注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
/**
* 方法描述
*/
String desc() default "";
}
- 自定义日志拦截器MyLogInterceptor
public class MyLogInterceptor extends HandlerInterceptorAdapter {
private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal();
@Override
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;
}
@Override
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) {
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 = myLog.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);
}
}
- 创建自动配置类MyLogAutoConfiguration,用于自动配置拦截器、参数解析器等web组件
@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyLogInterceptor());
}
}
- 在spring.factories中追加MyLogAutoConfiguration配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
it.cast.config.HelloServiceAutoConfiguration,\
it.cast.config.MyLogAutoConfiguration
- 测试
lombok
常用注解:
@Setter 类或属性
@Getter 类或属性
@ToString 类
@EqualsAndHashCode 类
@NoArgsConstructor 类
@RequireArgsConstor 类,构造器注入,属性需要使用final或者@NonNull注解标注
@AllArgsConstructor 所有构造方法
@Data setter/getter、equals、canEqual、hashCode、toString方法,如final属性,则不会为该属性生成setter方法
@Slf4j 类
@Builder 建造者模式