2021 最新版 Spring Boot 速记教程
好好学java
共 17155字,需浏览 35分钟
· 2021-02-05
点击上方 好好学java ,选择 星标 公众号
重磅资讯,干货,第一时间送达 今日推荐:分享一套基于SpringBoot和Vue的企业级中后台开源项目,这个项目有点哇塞!
个人原创100W +访问量博客:点击前往,查看更多
SpringBoot
,下面是简单的速记,根据使用场景可以快速定位到知识点:Demo
脚手架项目地址:SpringBoot 速记 一、引入依赖 二、配置 Swagger 参数 一、引入依赖 二、配置邮箱的参数 三、写模板和发送内容 一、引用 Redis 依赖 二、参数配置 三、代码使用 一、添加 mybatis 和 druid 依赖 二、配置数据库和连接池参数 三、其他 mybatis 配置 @ExceptionHandler 错误处理 @ModelAttribute 视图属性 常规配置 HTTPS 配置 构建项目 SpringBoot 基础配置 Spring Boot Starters @SpringBootApplication Web 容器配置 @ConfigurationProperties Profile @ControllerAdvice 用来处理全局数据 CORS 支持,跨域资源共享 注册 MVC 拦截器 开启 AOP 切面控制 整合 Mybatis 和 Druid 整合 Redis 发送 HTML 样式的邮件 整合 Swagger (API 文档) 总结 参考资料
构建项目
IDEA
的模板创建项目,我更推荐的是在 Spring
官网上选择参数一步生成项目。Generate the project
,下载到本地,然后使用 IDEA
打开Application
类的 run
方法就能直接启动项目。SpringBoot 基础配置
Spring Boot Starters
“ starter的理念:starter 会把所有用到的依赖都给包含进来,避免了开发者自己去引入依赖所带来的麻烦。需要注意的是不同的 starter 是为了解决不同的依赖,所以它们内部的实现可能会有很大的差异,例如 jpa 的 starter 和 Redis 的 starter 可能实现就不一样,这是因为 starter 的本质在于 synthesize,这是一层在逻辑层面的抽象,也许这种理念有点类似于 Docker,因为它们都是在做一个“包装”的操作,如果你知道 Docker 是为了解决什么问题的,也许你可以用 Docker 和 starter 做一个类比。 ”
SpringBoot
中很重要的一个概念就是,「约定优于配置」,通过特定方式的配置,可以减少很多步骤来实现想要的功能。Redis
在 pom
文件引入特定版本的redis
在 .properties
文件中配置参数根据参数,新建一个又一个 jedis
连接定义一个工具类,手动创建连接池来管理
Redis
Spring Boot
中,一切因为 Starter
变得简单在 pom
文件中引入spring-boot-starter-data-redis
在 .properties
文件中配置参数
bean
是 RedisAutoConfiguration
,自动配置类的名字都有一个特点,叫做 xxxAutoConfiguration
。@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate
Redis
自动配置类,读取了以 spring.redis
为前缀的配置,然后加载 redisTemplate
到容器中,然后我们在应用中就能使用 RedisTemplate
来对缓存进行操作~(还有很多细节没有细说,例如 @ConditionalOnMissingBean
先留个坑(●´∀`●)ノ)@Autowired
private RedisTemplate redisTemplate;
ValueOperations ops2 = redisTemplate.opsForValue();
Book book = (Book) ops2.get("b1");
@SpringBootApplication
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {...}
mian
方法:SpringApplication.run(SpringBootLearnApplication.class, args);
SpringApplicaiton
应用了。Web 容器配置
常规配置
HTTPS 配置
HTTPS
,可以参考这篇文章 Spring Boot 使用SSL-HTTPS@ConfigurationProperties
@Bean
注解所在方法上,这样 SpringBoot
就能够从配置文件中,读取特定前缀的配置,将属性值注入到对应的属性。@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidConfigBean {
private Integer initialSize;
private Integer minIdle;
private Integer maxActive;
private Listcustoms;
...
}
application.properties
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.customs=test1,test2,test3
Profile
SpringBoot
默认约定中,不同环境下配置文件名称规则为 application-{profile}.propertie
,profile
占位符表示当前环境的名称。application.properties
spring.profiles.active=dev
main
方法上添加 setAdditionalProfiles("{profile}")
;SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringBootLearnApplication.class);
builder.application().setAdditionalProfiles("prod");
builder.run(args);
java -jar demo.jar --spring.active.profile=dev
@ControllerAdvice 用来处理全局数据
@ControllerAdvice
是 @Controller
的增强版。主要用来处理全局数据,一般搭配 @ExceptionHandler
、@ModelAttribute
以及 @InitBinder
使用。@ExceptionHandler 错误处理
/**
* 加强版控制器,拦截自定义的异常处理
*
*/
@ControllerAdvice
public class CustomExceptionHandler {
// 指定全局拦截的异常类型,统一处理
@ExceptionHandler(MaxUploadSizeExceededException.class)
public void uploadException(MaxUploadSizeExceededException e, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write("上传文件大小超出限制");
out.flush();
out.close();
}
}
@ModelAttribute 视图属性
@ControllerAdvice
public class CustomModelAttribute {
//
@ModelAttribute(value = "info")
public MapuserInfo() throws IOException {
Mapmap = new HashMap<>();
map.put("test", "testInfo");
return map;
}
}
@GetMapping("/hello")
public String hello(Model model) {
Mapmap = model.asMap();
MapinfoMap = (Map ) map.get("info");
return infoMap.get("test");
}
key : @ModelAttribute
注解中的value
属性使用场景:任何请求 controller
类,通过方法参数中的Model
都可以获取value
对应的属性关注公众号Java后端编程,回复 Java 获取最新学习资料 。
CORS 支持,跨域资源共享
CORS(Cross-Origin Resource Sharing)
,跨域资源共享技术,目的是为了解决前端的跨域请求。“ 引用:当一个资源从与该资源本身所在服务器不同的域或端口请求一个资源时,资源会发起一个跨域HTTP请求 ”
demo
中,如果没有通过 Nginx
转发,那么将会提示如下信息:“ Access to fetch at ‘http://localhost:8888/login‘ from origin ‘http://localhost:3000‘ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’ ”
// 第一行,支持的域
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/login", method = RequestMethod.GET)
@ResponseBody
public String login(HttpServletResponse response) {
// 第二行,响应体添加头信息(这一行是解决上面的提示)
response.setHeader("Access-Control-Allow-Credentials", "true");
return HttpRequestUtils.login();
}
注册 MVC 拦截器
MVC
模块中,也提供了类似 AOP
切面管理的扩展,能够拥有更加精细的拦截处理能力。HandlerInterceptor
,使用方式如下:/**
* 自定义 MVC 拦截器
*/
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在 controller 方法之前调用
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在 controller 方法之后调用
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在 postHandle 方法之后调用
}
}
/**
* 全局控制的 mvc 配置
*/
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
// 表示拦截的 URL
.addPathPatterns("/**")
// 表示需要排除的路径
.excludePathPatterns("/hello");
}
}
preHandle
-> controller
-> postHandle
-> afterCompletion
,同时需要注意的是,只有 preHandle
方法返回 true
,后面的方法才会继续执行。开启 AOP 切面控制
Spring
时也有了解,可以参考我之前写过的文章参考一下:SpringBoot
中,使用起来更加简便,只需要加入该依赖,使用方法与上面一样。
org.springframework.boot
spring-boot-starter-aop
整合 Mybatis 和 Druid
SpringBoot
整合数据库操作,目前主流使用的是 Druid
连接池和 Mybatis
持久层,同样的,starter
提供了简洁的整合方案一、添加 mybatis 和 druid 依赖
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
com.alibaba
druid-spring-boot-starter
1.1.18
二、配置数据库和连接池参数
# 数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=12345678
# druid 配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-wait=60000
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.max-open-prepared-statements=20
spring.datasource.druid.validation-query=SELECT 1
spring.datasource.druid.validation-query-timeout=30000
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=false
#spring.datasource.druid.time-between-eviction-runs-millis=
#spring.datasource.druid.min-evictable-idle-time-millis=
#spring.datasource.druid.max-evictable-idle-time-millis=10000
# Druid stat filter config
spring.datasource.druid.filters=stat,wall
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
# session 监控
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.session-stat-max-count=10
spring.datasource.druid.web-stat-filter.principal-session-name=admin
spring.datasource.druid.web-stat-filter.principal-cookie-name=admin
spring.datasource.druid.web-stat-filter.profile-enable=true
# stat 监控
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.filter.stat.db-type=mysql
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=1000
spring.datasource.druid.filter.stat.merge-sql=true
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=mysql
spring.datasource.druid.filter.wall.config.delete-allow=true
spring.datasource.druid.filter.wall.config.drop-table-allow=false
# Druid manage page config
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
#spring.datasource.druid.stat-view-servlet.allow=
#spring.datasource.druid.stat-view-servlet.deny=
spring.datasource.druid.aop-patterns=cn.sevenyuan.demo.*
三、其他 mybatis 配置
xml
文件放入 resources
资源文件夹下,所以需要加入以下配置,让应用进行识别:
src/main/resources
**/*
...
SQL
、 URL
和 Sprint
监控,如下图:properties
文件中配置的参数,开启了 Druid
的监控。session
监控,所以如果需要配置 session
监控或者调整参数具体配置,可以查看官方网站整合 Redis
Redis
和 NoSQL
,但最熟悉和常用的,还是 Redis
,所以这里记录一下如何整合一、引用 Redis 依赖
org.springframework.boot
spring-boot-starter-data-redis
lettuce-core
io.lettuce
redis.clients
jedis
二、参数配置
# redis 配置
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
三、代码使用
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/testRedis")
public Book getForRedis() {
ValueOperationsops1 = stringRedisTemplate.opsForValue();
ops1.set("name", "Go 语言实战");
String name = ops1.get("name");
System.out.println(name);
ValueOperations ops2 = redisTemplate.opsForValue();
Book book = (Book) ops2.get("b1");
if (book == null) {
book = new Book("Go 语言实战", 2, "none name", BigDecimal.ONE);
ops2.set("b1", book);
}
return book;
}
发送 HTML 样式的邮件
一、引入依赖
org.springframework.boot
spring-boot-starter-mail
org.springframework.boot
spring-boot-starter-thymeleaf
二、配置邮箱的参数
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=xxxxxxxx
spring.mail.password=xxxxxxxx
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
QQ
邮箱,需要在邮箱的设置中获取授权码,填入上面的 password
中三、写模板和发送内容
MailServiceImpl.java
@Autowired
private JavaMailSender javaMailSender;
@Override
public void sendHtmlMail(String from, String to, String subject, String content) {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
javaMailSender.send(message);
} catch (MessagingException e) {
System.out.println("发送邮件失败");
log.error("发送邮件失败", e);
}
}
mailtemplate.html
"en" xmlns:th="http://www.thymeleaf.org">
"UTF-8">
邮件 "${subject}">书籍清单
"1">
图书编号
图书名称
图书作者
"book:${books}">
"${book.id}">
"${book.name}">
"${book.author}">
test.java
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@Test
public void sendThymeleafMail() {
Context context = new Context();
context.setVariable("subject", "图书清册");
Listbooks = Lists.newArrayList();
books.add(new Book("Go 语言基础", 1, "nonename", BigDecimal.TEN));
books.add(new Book("Go 语言实战", 2, "nonename", BigDecimal.TEN));
books.add(new Book("Go 语言进阶", 3, "nonename", BigDecimal.TEN));
context.setVariable("books", books);
String mail = templateEngine.process("mailtemplate.html", context);
mailService.sendHtmlMail("xxxx@qq.com", "xxxxxxxx@qq.com", "图书清册", mail);
}
整合 Swagger (API 文档)
一、引入依赖
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
二、配置 Swagger 参数
SwaggerConfig.java
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
@Bean
Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("cn.sevenyuan.demo.controller"))
.paths(PathSelectors.any())
.build().apiInfo(
new ApiInfoBuilder()
.description("Spring Boot learn project")
.contact(new Contact("JingQ", "https://github.com/vip-augus", "=-=@qq.com"))
.version("v1.0")
.title("API 测试文档")
.license("Apache2.0")
.licenseUrl("http://www.apache.org/licenese/LICENSE-2.0")
.build());
}
}
UI
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60)
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
@ApiOperation
等接口标志,在网页查看 API
文档,参考文档:Spring Boot实战:集成Swagger2总结
resources
目录的 test.sql
文件中参考资料
推荐文章
点击关注下方公众号,回复「算法」获取
评论
超赞!这个ChatGPT提问教程,PDF免费下载
你好,我是郭震AI来袭,我们该如何学习?今天先分享给大家一份超好的GPT提问指南。教程的详细介绍参考下面视频:这个PDF资料旨在教我们更好的给GPT发送指令,让GPT更准确的回答我们的提问。一共有30页,内容包括7个小章节,按照逻辑展开。分别介绍文本回答,代码辅助,结构化结果输出,非结构化结构输出,
Python与算法社区
3
Spring Boot + flowable 快速实现工作流
关注我们,设为星标,每天7:40不见不散,架构路上与您共享回复架构师获取资源大家好,我是你们的朋友架构君,一个会写代码吟诗的架构师。来源:blog.csdn.net/zhan107876/article/details/120815560总览一、flowable-ui部署运行二、绘制流程图绘图细节:
Java架构师社区
0
侠盗猎车手免安装教程,支持安卓+PC!
前几天有粉丝朋友问我有没有侠盗猎车手罪恶都市这个游戏,今天就从解决实际问题的角度上,亲测这款游戏从安装到试玩,当然这篇文章使用的免安装版本,方便大家解压即玩!废话不多说先来看一下实测结果吧,我两台电脑都可以玩,一台是Win10,一台是Win11免安装,解完压缩就可以直接玩:非常经典的游戏开始画面:《
dotNET全栈开发
10
2024版,尚硅谷Java学科全套教程(289.1GB),含最新技术
尚硅谷 Java 学科全套视频,很早之前分享过一次,大概是 200G 左右,今天这个是《2024 版尚硅谷 Java 学科全套教程》,新增了 80 多个 GB,里面涵盖了 2023 年、2024 年最新更新的技术,基本上涵盖了 Java 所有的技术,共 289.1GB,文末附网盘地址。目录 基础部分
路人甲Java
0
Spring Boot 优雅实现多租户架构
来源:blog.csdn.net/u010349629/article/details/130737253👉 欢迎加入小哈的星球 ,你将获得: 专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡 / 赠书福利全栈前后端分离博客项目 2.0
小哈学Java
1448
美团一面:为什么 Spring 和 IDEA 都不推荐使用 @Autowired 注解??
点击关注公众号,Java 干货及时推送↓推荐阅读:铜三铁四,怒拿 35K * 14 薪!作者:小亮哥Ya链接:https://juejin.cn/post/7080441168462348319大家在使用IDEA开发的时候有没有注意到过一个提示,在字段上使用Spring的依赖注入注解@Au
Java技术栈
0
目前工资最高的几家外包公司汇总!(2024最新版)
最近,很多小伙伴问:只有外包的 offer 能去吗?大环境不行,面试太少了,很多本科生想进外包都没机会。非常时期,不需要在意那么多,外包作为过渡也是没问题的,很多外包其实比小公司还要好多了。也不要太担心去外包会污染自己的简历,只要接触的项目还可以,写在简历上再润色一下,那就完全没问题的,放心!默默沉
程序IT圈
0
终于来了,2024 最新版 SpringCloud 教程,收藏好,慢慢看
2024 最新版 SpringCloud 最强教程来了,目录如下,文末附教程地址。SpringCloud-前言闲聊开篇简介01_SpringBoot和SpringCloud版本选型02_SpringCloud是什么能干吗03_SpringCloud各组件的停更升级替换说明04_项目实战之需求说明05
路人甲Java
0