SpringBoot学习

SpringBoot是什么

约定大于配置
简化版javaWeb开发框架,开箱即用
对比spring配置大大减少

微服务:架构风格

配置编写yaml

配置文件能配置什么?

  1. 官方文档
  2. 了解原理

配置格式:
application.properties: key=value
application.yaml:key: 空格value

语法:

# 普通的key-value
name: yangs

# 对象
student: 
	name: yangs
	age: 1
# 行内写法
student: {name: yangs, age: 1}

# 数组
pets: 
	- cat
	- dog
	- pig
# 行内写法
pets: [cat, dog, pig]

使用配置文件与java类绑定,为其属性赋值
方法一 :
.yaml配置文件,可以使用表达式配置默认值等
在对应的类上添加注解:
@ConfigurationProperties(prefix=“.yaml中的key名”)

方法二:
.properties配置文件

  1. 先在类上添加注解:@PropertySource(value = “classpath:application.properties”)
  2. 在对应的字段上添加注解 @Value(“&{key名}”)

两种配置文件对比
在这里插入图片描述
.yaml文件对比.properties 可用保存对象,数组,但是对空格要求高
.properties 只能存键值对,如:student.name = yangs

JSR303校验
yaml支持JSR303校验

  1. @Validated 在类上添加该注解,开启数据校验
  2. 在需要校验的字段上加注解,如@Email,校验是否为邮箱格式

多环境配置

  1. properties中:
    spring.profiles.active = dev #定义环境名
  2. yaml中:
server: 
	port: 8080
spring: 
	profiles: 
		active: dev
---
server: 
	port: 8081
spring: 
	profiles: 
		active: test

自动装配

自动配置原理:

pom.xml

  • 核心依赖在父工程中:spring-boot-dependencies
  • 在引入或写springboot依赖时,不需要指定版本,因为已经存在版本仓库
  • 启动器:spring-boot-starter,根据使用场景引入,如:spring-boot-starter-web
  • 打包插件

主程序:

  • @SpringBootApplication:标注这个类是springboot的应用,启动类下的所有资源被导入

  • @SpringBootConfiguration
    –@Configuration:spring配置类
    ----@Component:说明是一个组件类

  • @EnableAutoConfiguration:自动配置
    – @AutoConfigurationPackage:自动配置包
    ----@Import({AutoConfigurationPackages.Registrar.class}):自动配置包注册
    – @Import({AutoConfigurationImportSelector.class}):导入选择器
    ---- getAutoConfigurationEntry:获取自动配置实体
    ---- getCandidateConfigurations:获取候选配置
    ------ SpringFactoriesLoader.loadFactoryNames:加载核心自动配置文件
    -------- getSpringFactoriesLoaderFactoryClass:获取所有被@EnableAutoConfiguration注解标注的类(@SpringBootApplication)

自动配置核心文件:META-INF/spring.factories
在这里插入图片描述
自动配置文件导入包:META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
在这里插入图片描述
结论:springboot所有的自动配置都是在启动的时候扫描并加载:spring.factories。但不一定生效,只要导入了对于的starter自动配置才会生效
核心注解:@ConditionalOnxxx
在这里插入图片描述

run方法

  1. 推断项目是普通项目还是web项目
  2. 查找加载所有可能的初始化器
  3. 设置所有可用程序的监听器:全局有效,获取上下文和bean
  4. 推断并设置main方法的定义类
    核心:javaConfig @Configuration @Bean

配置文件装配原理
@EnableConfigurationProperties

精髓

  1. SpringBoot启动会加载大量的自动配置类
  2. 我们看需要的概念是否在springboot默认写好的自动配置类中
  3. 再看这个自动配置类中到达配置了哪些组件(如果我们要用的组件已存在其中,就无需手动配置了)
  4. 给容器中自动配置的类添加组件的时候,会从properties类中获取某些属性,我们只需要在配置文件中给这些属性赋值即可
  5. xxxAutoConfiguration:自动配置类,给容器中添加组件
  6. xxxProperties:封装配置文件中相关属性

查看组件是否生效
在配置文件中配置 debug = true,启动时,日志打印

集成web开发

要解决的问题:

  • 导入静态资源
  • 首页
  • jsp,模板引擎Thymeleaf
  • 装配扩展springMVC
  • 增删改查
  • 拦截器
  • 国际化

静态资源
处理静态资源的方法

  1. 导入webjars,通过依赖(不推荐使用)
  2. 在指定路径下添加:classpath下的文件夹:public、static(默认)、/**、resources
    http//:localhost:8080
        private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
  1. 优先级:resources>static>public

首页
需要模板引擎的支持,thymeleaf接管所有的静态资源,@{}

Thymeleaf模板引擎

  1. 导入依赖
  2. 源码:ThymeleafProperties
  3. 将html放在templates目录下
  4. html中导入thymeleaf约束 th:
  5. 所有html元素都能被thymeleaf替换接管

Thymeleaf语法
官网:https://www.thymeleaf.org/

MVC装配
实现WebMvcCongfigurer接口
实现ViewResolver 视图解析器接口,重写resolverViewName方法
底层调用doDispatcher方法

在springboot中,有非常多的xxxxConfiguration帮助我们扩展配置,看到这个类就要注意看他扩展了哪些功能!

国际化

  1. 置i18n文件
  2. 在项目中进行按钮自动切换,需要自定义一个组件LocaleResolver
  3. 记得将自己的组件配置到spring容器中,@Bean
  4. #{}

拦截器
登录后才能访问首页

前端

  1. 模板
  2. 框架:bootstrap、layui、…
    x-admin

集成数据库开发

spring-data

Druid后台监控

ServletRegistrationBean
FilterRegistrationBean

Mybatis整合

  1. 导包 mybatis-spring-boot-starter
  2. 配置数据源
  3. mybatis配置
  4. 写SQL

分布式开发 Dubbo+Zookeeper

Dubbo

Dubbo是一款高性能、轻量级的开源Java RPC框架,它提供了三大核心能力:

  • 面向接口的远程方法调用
  • 智能容错和负载均衡
  • 服务自动注册和发现
    官方文档:https://dubbo.incubator.apache.org/zh/overview/
    在这里插入图片描述
    Provider:提供者
    Consumer:消费者
    Register:注册中心
    Monitor:监控中心

什么是RPC

Remote Procedure Call 远程过程调用(跨服务器调用)
两个核心模块:通信、序列化

Zookeeper

注册中心,提供了分布式独享锁、选举、队列的接口。

工具:dubbo-admin
是一个监控管理后台,可以监控注册了哪些服务,哪些服务被消费了

整合springboot

  1. 导依赖
<!-- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo-spring-boot-starter -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>3.0.10</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
<dependency>
    <groupId>com.github.sgroschupf</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.1</version>
</dependency>

  1. 消费者配置文件,注册中心
dubbo:
  application:
    name: dubbo-springboot-demo-provider
  protocol:
    name: dubbo
    port: -1
  registry:
    id: zk-registry
    address: zookeeper://127.0.0.1:2181
  config-center:
    address: zookeeper://127.0.0.1:2181
  metadata-report:
    address: zookeeper://127.0.0.1:2181
  1. 启动类加上@EnableDubbo注解
@SpringBootApplication
@EnableDubbo
public class ProviderApplication {
    public static void main(String[] args) throws Exception {
        new EmbeddedZooKeeper(2181, false).start();

        SpringApplication.run(ProviderApplication.class, args);
        System.out.println("dubbo service started");
        new CountDownLatch(1).await();
    }
}
  1. 接口类
public interface DemoService {
    String sayHello(String name);
}
  1. 编写接口实现类,提供者
//@Service //dubbo包下的
@Component //尽量不使用Service,会与dubbo的重名
@DubboService //2.2.7版本以上使用
public class DemoServiceImpl implements DemoService {
    @Override
    public String sayHello(String name) {
        System.out.println("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
        return "Hello " + name;
    }
}
  1. 消费者配置文件
dubbo:
  application:
    name: dubbo-springboot-demo-provider
  protocol:
    name: dubbo
    port: -1
  registry:
    id: zk-registry
    address: zookeeper://127.0.0.1:2181
  config-center:
    address: zookeeper://127.0.0.1:2181
  metadata-report:
    address: zookeeper://127.0.0.1:2181
  1. 消费者引用远程服务
public class ConsumerApplication {
    @DubboReference
    private DemoService demoService;
}
  1. 消费者调用远程服务
@SpringBootApplication
@Service
@EnableDubbo
public class ConsumerApplication {
    @DubboReference
    private DemoService demoService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(ConsumerApplication.class, args);
        ConsumerApplication application = context.getBean(ConsumerApplication.class);
        String result = application.doSayHello("world");
        System.out.println("result: " + result);
    }
}

注意:@EnableDubbo 是必须的

Swagger:接口文档

简介

前后端分离主流框架: Vue + SpringBoot
后端:后端控制层、服务层、数据访问层
前端:前端控制层、视图层
前后端交互:API接口
** Swagger**

  • 号称最流行的API框架
  • RestFul风格 API文档在线自动生成工具 ==》API定义与API接口文档同步更新
  • 直接运行,可以在线测试API接口
  • 支持多种语言

springboot集成swagger

  1. 新建springboot web项目
  2. 导依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
  1. 创建swagger配置类
  • 使用@EnableSwagger2注解
  • 配置swagger的docket的bean实例
  • 自定义swagger的apiInfo信息

测试访问swagger: http://localhost:8080/swagger-ui.html

swagger配置扫描接口

Docket的方法:

new Docket(DocumentationType.SWAGGER_2)
//配置swagger信息
.apiInfo(new ApiInfo())
//默认true,false时浏览器中无法访问swagger:http://localhost:8080/swagger-ui.html
.enable(false) 
//配置扫描接口
.select()
//配置要扫描接口的方式:any,none,basePackage,withClassAnnotation,withMethodAnnotation
.api(RequestHandlerSelectors.basePackage("包名")) 
.build();

配置API文档分组

.groupName("组名")

配置多个分组:

@Bean
public Docket docket1(){
	return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket1(){
	return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}

配置文档注释

//1. 控制类注释
@ApiOperation(“”)
//2. 实体类注释 == 等价@Api(“”)
@ApiModel(“”)
//3. 属性注释
@ApiModelProperty(“”)

总结

使用swagger的好处:

  1. 给一些比较难理解的属性或接口,增加注释信息
  2. 接口文档实时更新
  3. 可以在线测试
    【注意点】在正式发布的时候,关闭swagger!!!出于安全考虑,且节省内存。

任务调度

异步任务

  1. 在启动类上添加@EnableAync开启异步注解
  2. 在控制类的方法上使用@Aync开启异步功能

定时任务

TaskScheduler 任务调度名
TaskExecutor 任务执行者
@EnableScheduling //开启定时功能的注解
@Scheduled //什么时候执行
cron表达式

cron表达式
秒 分 时 日 月 周几
0 10 10 * * ? //每天的10点10分0秒执行
30 0/5 10,18 * * ? //每天10点和18点每5分钟执行

@Scheduled(cron = “0 10 10 * * ?”)

邮件发送

  1. 导包 springboot-starter-mail (javax.mail)
  2. 配置文件中配置邮箱信息
  3. 编写邮箱发送控制类
  • 自动注入JavaMailSenderImpl类 mailSender
  • 配置邮件信息
    简单邮件 SimpleMailMessage msg
    复杂邮件 MimeMessage msg、通过MimeMessageHelper组装
  • 发送邮件:mailSender.send(msg)

springSecurity(安全)

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

核心功能

  1. 用户认证
  2. 授权(访问控制)

Shiro

核心功能:

  1. 授权
  2. 认证

三大核心组件:

  1. subject 当前用户
  2. securityManager 管理所有用户
  3. realm 连接数据

shiro内置过滤对象:

anno:无需认证就可以访问
authc:需要认证后才能范围
user:必须拥有记住我功能才能用
perms:拥有对某个资源的权限才能访问
role:拥有某个角色权限才能访问

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值