随着 Java Spring 框架的不断的更新迭代和封装,演变出用最少的代码,干多个功能的 Spring Boot 框架。
今天无脑将介绍 Spring Boot 框架的基本使用,分享给大家,希望帮助大家大幅提高开发能力!

SpringBoot是由Pivotal团队研发的,SpringBoot并不是一门新技术,只是将之前常用的Spring,SpringMVC,data-jpa等常用的框架封装到了一起,帮助你隐藏这些框架的整合细节,实现敏捷开发。
SpringBoot就是一个工具集。
| LOGO |
|
|
主要组件:
Spring Boot 中的 Spring MVC(Model-View-Controller)执行流程与传统的 Spring MVC 框架类似,但在 Spring Boot 中进行了一些自动配置,以简化开发和配置。以下是 Spring Boot 中 Spring MVC 的主要执行流程:
这里建议大家,使用 2022 版本以上的 IDAE ,Java 17 以上,本人是使用以上版本的。
这几个依赖内置了 tomcat、spring、spring MVC 的依赖,简化依赖的冗余。
org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-testtest org.projectlombok lombok1.18.26 org.springframework.boot spring-boot-maven-plugin
/**
* 权限实体类
*
* @author 无戏
* @date 2023/10/31
*/
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class Permission {
private Integer id;
private String name;
private String type;
private Integer isDeleted;
}
/**
* 用户实体类
* @author 无戏
*/
@Component
//Type-Safe(类型安全的),prefix:文件名前缀
@ConfigurationProperties(prefix = "user")
//加载 book.properties 配置文件到 Spring 容器中,这个相当于 XML 中的 placeholder 配置
@PropertySource("classpath:user.properties")
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class User {
/**
* 直接获取 properties 配置文件的对应键的值
* @Value("${user.id}")
*/
private Integer id;
/**
* @Value("${user.password}")
*/
private String password;
//@Value("${user.imgUrl}")
private String imgUrl;
//@Value("${user.rId}")
private Integer rId;
//@Value("${user.isDeleted}")
private Integer isDeleted;
private Permission permission;
private Permission[] permission2;
private List permission3;
private Map permission4;
}
user.permission.name=1 user.permission.type=ss user.permission.isDeleted=1 user.permission2[0].id=2 user.permission2[0].name=3 user.permission2[0].type=ss1 user.permission2[0].isDeleted=0 user.permission3[0]=2 user.permission3[1]=3 user.permission3[2]=ss1 user.permission4.id=2
/**
* 用户实体类
* @author 无戏
*/
@Component
@ConfigurationProperties(prefix = "user")
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class User {
/**
* @Value("${user.id}")
*/
private Integer id;
/**
* @Value("${user.password}")
*/
private String password;
//@Value("${user.imgUrl}")
private String imgUrl;
//@Value("${user.rId}")
private Integer rId;
//@Value("${user.isDeleted}")
private Integer isDeleted;
private Permission permission;
private Permission[] permission2;
private List permission3;
private Map permission4;
}
配置文件名以 appliaction 开头
user:
id: 1110
password: 123456
imgUrl: null
rId: 10
isDeleted: 1
permission:
id: 999
name: 超级管理员
type: 1
isDeleted: 1
permission2:
- id: 9992
name: 超级管理员
type: 1
isDeleted: 1
- id: 9993
name: 超级管理员
type: 1
isDeleted: 1
permission3:
- 4
- 5
- 6
permission4:
a: b
b: c
SpringBoot的配置文件支持 properties 和 yml ,甚至他还支持 json。
更推荐使用 yml 文件格式:
yml文件的劣势:
# 获取 java 版本号 myjava=@java.version@ # 17 # 修改 Tomcat 端口号 server.port=8081 server.servlet.context-path=/d # 配置 URL 编码格式,这个默认就是 UTF-8 server.tomcat.uri-encoding=UTF-8
# 配置执行的环境,如生产环境(prod)、测试环境(test)、开发环境(dev) spring.profiles.active=test
生产环境:
server.port=8090
开发环境:
server.port=8090
测试环境:
server.port=99
# 自定义静态资源访问规则 spring.mvc.static-path-pattern=/qf/** # 自定义静态资源路径 spring.web.resources.static-locations=classpath:qf/
# JDBC 驱动 spring.datasource.url=jdbc:mysql://localhost:3306/xmbg?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false # mysql 用户名 spring.datasource.username=root # 密码 spring.datasource.password=1234
mybatis-plus.configuration.map-underscore-to-camel-case=false
控制层:
/**
* @author 无戏
* @projectName 控制层
* @date 2023/11/1 9:58
*/
@RestController
public class UserController {
@GetMapping("/hello")
public User hello(){
return User.builder().id(5555).password(new Date()).build();
}
}
实体类;
/**
* 用户实体类
* @author 无戏
*/
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class User {
private Integer id;
private Date password;
}
org.springframework.boot spring-boot-starter-web
配置类:
/**
* @author 无戏
* @projectName 格式化时间
* @date 2023/11/1 15:14
*/
@Configuration
public class WebConfig {
@Bean
ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
return objectMapper;
}
}
com.google.code.gson gson
/**
* @author 无戏
* @projectName 格式化时间
* @date 2023/11/1 15:14
*/
@Configuration
public class WebConfig {
@Bean
GsonBuilder gsonBuilder() {
return new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss");
}
}
com.alibaba fastjson1.2.70
/**
* @author 无戏
* @projectName 格式化时间
* @date 2023/11/1 15:14
*/
@Configuration
public class WebConfig {
@Bean
HttpMessageConverter httpMessageConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8"));
return converter;
}
}
# 文件保存目录 savePath=E:\Datas\file
/**
* @author 无戏
* @projectName
* @date 2023/11/1 9:58
*/
@RestController
public class UserController {
private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("/yyyy/MM/dd/");
@Value("${savePath}")
private String savePath;
@GetMapping("/hello")
public User2 hello(){
return User2.builder().id(5555).password(new Date()).build();
}
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request){
LocalDateTime now = LocalDateTime.now();
String format = now.format(dtf);
String path = savePath + format;
File file1 = new File(path);
if (!file1.exists()) {
file1.mkdirs();
}
String filename = file.getOriginalFilename();
String newFileName = UUID.randomUUID().toString() + filename.substring(filename.indexOf("."));
try {
file.transferTo(new File(path, newFileName));
return request.getScheme()
+ "://"
+ request.getServerName()
+ ":"
+ request.getServerPort()
+ request.getContextPath()
+ "/upload"
+ format + newFileName;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* @author 无戏
* @projectName
* @date 2023/11/1 9:58
*/
@RestController
public class UserController {
private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("/yyyy/MM/dd/");
@Value("${savePath}")
private String savePath;
@GetMapping("/upload/{year}/{month}/{day}/{filename}")
public void download(@PathVariable String year, @PathVariable String month,
@PathVariable String day, @PathVariable String filename,
HttpServletResponse response) throws IOException {
File file = new File(savePath + File.separator + year + File.separator + month + File.separator + day
+ File.separator + filename);
//有这个响应头,就是文件下载,没有这个响应头,就是访问
response.setHeader("content-disposition", "attachment;filename="
+ new String(filename.getBytes("UTF-8"), "ISO-8859-1"));
ServletOutputStream os = response.getOutputStream();
FileInputStream fs = new FileInputStream(file);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fs.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
os.flush();
fs.close();
}
}
/**
* @author 无戏
* @projectName
* @date 2023/11/1 9:58
*/
@RestController
public class UserController {
@GetMapping("/upload2/{year}/{month}/{day}/{filename}")
public ResponseEntity download2(@PathVariable String year, @PathVariable String month,
@PathVariable String day, @PathVariable String filename, HttpServletResponse response) throws IOException {
File file = new File(savePath + File.separator + year + File.separator + month + File.separator + day
+ File.separator + filename);
FileInputStream fs = new FileInputStream(file);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fs.read(bytes)) != -1) {
aos.write(bytes, 0, len);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("filename", new String(filename.getBytes("UTF-8"), "ISO-8859-1"));
//第一个参数是文件本身
//第二个是响应头
//第三个是 HTTP 状态码
return new ResponseEntity<>(aos.toByteArray(), headers, HttpStatus.OK);
}
}
Spring Boot 中默认提供了五个静态资源存储路径:
五个位置,优先级依次降低。
如果需要自定义静态资源位置,有两种方式:
# 自定义静态资源访问规则 spring.mvc.static-path-pattern=/qf/** # 自定义静态资源路径 spring.web.resources.static-locations=classpath:qf/
/**
* @author 无戏
* @projectName 自定义静态资源位置
* @date 2023/11/1 15:14
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/qf/**")
.addResourceLocations("classpath:qf/");
}
}
Spring MVC 的数据模型通常是通过控制器传递给视图的数据对象,用于呈现给用户界面。数据模型的主要目的是在控制器和视图之间传递数据。
这是一个相当老牌的开源的免费的模版引擎,基于Apache许可证2.0版本发布。 通过 Freemarker 模版,我们可以将数据渲染成 HTML 网页、电子邮件、配置文件以及源代码等。
Freemarker 不是面向最终用户的,而是一个 Java 类库,我们可以将之作为一个普通的组件嵌入到我们 的产品中。
可以看到,Freemarker 可以将模版和数据渲染成 HTML 。 Freemarker 模版后缀为 .ftlh (FreeMarker Template Language)。FTL 是一种简单的、专用的语言, 它不是像 Java 那样成熟的编程语言。在模板中,你可以专注于如何展现数据, 而在模板之外可以专注 于要展示什么数据。

导入依赖 :
org.springframework.boot spring-boot-starter-freemarker
Title
<#if users?? && (users?size>0)>
| 用户名 | 用户地址 | 用户爱好 | 用户生日 |
| ${user.username} | ${user.address} | <#list user.favorites as f> ${f}; #list> | ${user.birthday?string('yyyy-MM-dd')} |
第一种写法:
/**
* @author 无戏
*/
@Controller
public class UserController {
@GetMapping("/hello")
public ModelAndView hello() {
//传入视图名称
ModelAndView mv = new ModelAndView("hello");
List users = new ArrayList<>();
User u1 = new User();
u1.setUsername("张三");
u1.setAddress("广州");
u1.setBirthday(new Date());
List f1 = new ArrayList<>();
f1.add("足球");
f1.add("篮球");
u1.setFavorites(f1);
users.add(u1);
User u2 = new User();
u2.setUsername("里斯");
u2.setAddress("深圳");
u2.setBirthday(new Date());
List f2 = new ArrayList<>();
f2.add("乒乓球");
f2.add("篮球");
u2.setFavorites(f2);
users.add(u2);
mv.addObject("users", users);
return mv;
}
}
第二种写法:
/**
* @author 无戏
*/
@Controller
public class UserController {
@GetMapping("/hello")
public String hello(Model model) {
//传入视图名称
//ModelAndView mv = new ModelAndView("hello");
List users = new ArrayList<>();
User u1 = new User();
u1.setUsername("张三");
u1.setAddress("广州");
u1.setBirthday(new Date());
List f1 = new ArrayList<>();
f1.add("足球");
f1.add("篮球");
u1.setFavorites(f1);
users.add(u1);
User u2 = new User();
u2.setUsername("里斯");
u2.setAddress("深圳");
u2.setBirthday(new Date());
List f2 = new ArrayList<>();
f2.add("乒乓球");
f2.add("篮球");
u2.setFavorites(f2);
users.add(u2);
model.addAttribute("users", users);
return "hello";
}
}
Thymeleaf 是新一代 Java 模板引擎,它类似于 Velocity、FreeMarker 等传统 Java 模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型。
它既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,因此在 SpringBoot 中使用Thymeleaf 非常方便。
事实上, Thymeleaf 除了展示基本的 HTML ,进行页面渲染之外,也可以作为一个 HTML 片段进行渲染,例如我们在做邮件发送时,可以使用 Thymeleaf 作为邮件发送模板。另外,由于 Thymeleaf 模板后缀为.html ,可以直接被浏览器打开,因此,预览时非常方便。
org.springframework.boot spring-boot-starter-thymeleaf
Title
| 用户名 | 用户地址 | 用户生日 | 用户爱好 |
| ; |
/**
* @author 无戏
*/
@Controller
public class UserController {
@GetMapping("/hello")
public String hello(Model model) {
//传入视图名称
List users = new ArrayList<>();
User u1 = new User();
u1.setUsername("张三");
u1.setAddress("广州");
u1.setBirthday(new Date());
List f1 = new ArrayList<>();
f1.add("足球");
f1.add("篮球");
u1.setFavorites(f1);
users.add(u1);
User u2 = new User();
u2.setUsername("里斯");
u2.setAddress("深圳");
u2.setBirthday(new Date());
List f2 = new ArrayList<>();
f2.add("乒乓球");
f2.add("篮球");
u2.setFavorites(f2);
users.add(u2);
model.addAttribute("users", users);
List links = new ArrayList<>();
Link l1 = new Link();
l1.setName("百度一下");
l1.setUrl("http://www.baidu.com");
links.add(l1);
Link l2 = new Link();
l2.setName("Google");
l2.setUrl("http://www.google.com");
links.add(l2);
model.addAttribute("links", links);
return "hello";
}
}
项目结构:必须在 web 模块的 web 或 webapp 目录下。

org.apache.tomcat.embed tomcat-embed-jasper
<%--
Created by IntelliJ IDEA.
User: 无戏
Date: 2023/11/2
Time: 12:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
${hello}
/**
* @author 无戏
*/
@Controller
public class UserController {
@GetMapping("/hello")
public String hello2(Model model) {
//
model.addAttribute("hello", "hello jsp");
return "hello";
}
}
整体来说两种方式:
具体查找方式:
# 表示是否展示异常类名 server.error.include-exception=true # always(一直展示)或 never(不展示) # 表示是否展示错误堆栈信息 server.error.include-stacktrace=always # 表示是否展示错误信息 server.error.include-message=always
报错页面展示效果:

模板页面代码:
error
01.ftlh(动态)
| error | ${error!} |
| message | ${message!} |
| timestamp | ${timestamp?string('yyyy-MM-dd HH:mm:ss')} |
| status | ${status!} |
| path | ${path!} |
| exception | ${exception!} |
| e | ${e!} |
| trace | ${trace!} |
如下图:

自定义异常信息:
/**
* @author 无戏
* @projectName 自定义异常信息
* @date 2023/11/2 19:15
*/
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
@Override
public Map getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map errorAttributes = super.getErrorAttributes(webRequest, options);
errorAttributes.put("e", "出错了");
return errorAttributes;
}
}
自定义异常访问的位置:
/**
* @author 无戏
* @projectName 自定义异常访问的位置
* @date 2023/11/2 19:19
*/
@Component
public class MyErrorViewResolver extends DefaultErrorViewResolver {
/**
* 我错误视图解析器
*
* @param applicationContext 应用程序上下文
* @param webProperties web属性
*/
public MyErrorViewResolver(ApplicationContext applicationContext, WebProperties webProperties) {
super(applicationContext, webProperties.getResources());
}
/**
* 解析错误视图
*
* @param request 要求
* @param status 地位
* @param model 模型
* @return {@link ModelAndView}
*/
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map model) {
//model.put("e", "出错啦");
return new ModelAndView("qf/01", model);
}
}
org.springframework.boot spring-boot-starter-weborg.mybatis.spring.boot mybatis-spring-boot-starter3.0.2 com.mysql mysql-connector-jruntime org.projectlombok lomboktrue org.springframework.boot spring-boot-starter-tomcatprovided org.springframework.boot spring-boot-starter-testtest org.mybatis.spring.boot mybatis-spring-boot-starter-test3.0.2 test
spring.datasource.url=jdbc:mysql://localhost:3306/xmbg?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false spring.datasource.username=root spring.datasource.password=1234 # 映射文件的路径,第二种方法使用 # mybatis.mapper-locations=classpath*:mapper/*.xml
如UserMapper.xml 位置为 UserMapper接口的全路径:

推荐使用:
只需在 application.properties 文件里加映射文件资源位置就行,如下所示:
spring.datasource.url=jdbc:mysql://localhost:3306/xmbg?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false spring.datasource.username=root spring.datasource.password=1234 # 映射文件的路径,第二种方法使用 mybatis.mapper-locations=classpath*:mapper/*.xml

/**
* @author 无戏
* @projectName
* @date 2023/11/2 20:38
*/
@Mapper
public interface UserMapper {
/**
* 全选
*
* @return {@link List}<{@link User}>
*/
List selectAll();
}
@MapperScan 是使用 MyBatis 框架时用于指定扫描 Mapper 接口的包或类路径的注解。该注解可以用于在 Spring Boot 环境中自动将 Mapper 接口注册为 Spring Bean。
@MapperScan 注解有三个重要的属性:
@MapperScan("com.example.mapper")
@MapperScan(basePackages = {"com.example.mapper1", "com.example.mapper2"})
@MapperScan(basePackageClasses = UserMapper.class)
在这个例子中,UserMapper 是一个 Mapper 接口类,@MapperScan 注解会自动扫描该接口所在的包路径下的所有 Mapper 接口。
使用 @MapperScan 注解可以快速设置所有 Mapper 接口。如果您要扫描多个包或类路径,可以使用数组的形式,或者使用多个 value 属性。在您指定了需要扫描的 Mapper 接口所在的类或类路径后,MyBatis 框架就会自动查找 Mapper 接口,并将其注册为 Spring Bean。
/**
* @author 无戏
* @projectName
* @date 2023/11/2 20:38
*/
public interface UserMapper {
/**
* 全选
*
* @return {@link List}<{@link User}>
*/
List selectAll();
}
@SpringBootApplication:是一个组合注解,包含以下注解。
@EnableAutoConfiguration:启用Spring Boot的自动配置机制,根据应用程序的类路径和依赖自动配置Spring应用。
ConfigurationProperties:是 Spring Boot 中一个重要的注解,用于绑定配置属性到一个 Java 类。这允许您将应用程序的配置属性加载到一个 POJO(Plain Old Java Object)中,以便更方便地使用和管理这些属性。
@PathVariable:用于从URL中提取路径变量,通常用于RESTful风格的URL。
@RequestParam:用于从HTTP请求中获取请求参数的值。
@Configuration:用于定义配置类,可以包含@Bean注解的方法,以配置应用程序中的bean。
@DateTimeFormat:用于指定日期字段的格式化方式,以将字符串表示的日期转换为Java日期对象。
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date date;
@JsonFormat:用于指定日期字段在JSON序列化和反序列化时的格式。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date date;
@Value:用于注入配置属性值,例如从application.properties文件中获取值。
@Value("${user.password}")
private String password;
@EnableScheduling:用于启用Spring定时任务(Scheduled Task),允许在指定的时间间隔内执行方法。用于启用 Spring 的计划任务(Scheduling)支持,允许您在应用程序中使用 @Scheduled 注解来定义定时任务。
@Scheduled:注解允许您将方法标记为定时任务,您可以使用不同的参数来配置任务的执行方式。以下是 @Scheduled 注解的主要参数说明:
@Configuration
@EnableScheduling
public class ScheduledTasks {
@Scheduled(fixedRate = 5000) // 每5秒执行一次
public void doTask() {
// ...
}
}
@ComponentScan 注解用于告诉 Spring Boot 在哪里查找 Spring 组件(bean),并注册它们到应用程序上下文中。通常,您将在配置类上使用 @ComponentScan 来指定一个或多个包,Spring Boot 将扫描这些包以查找带有 @Component 或其他特定注解的类,并将它们自动注册为 Spring 组件。
以下是 @ComponentScan 的基本用法示例:
@Configuration
@ComponentScan(basePackages = "com.example.myapp")
public class AppConfig {
// 配置类的其他内容
}
以上就是本期分享,希望对大家有帮助吧~
走过路过关注一波儿吧,感谢!
有 三连 的给个 三连 ,没三连的 给个点赞 也是美滋滋的,谢谢各位大佬。
我是无脑,点赞 + 在看 还是想求一下的,祝大家都能心想事成、发大财、行大运。
