🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
SpringBoot核心知识点全解析:从入门到精通的必备指南
一、SpringBoot简介
1.1 SpringBoot的定义
Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的配置方式,从而使开发人员不再需要定义样板化的配置。
1.2 SpringBoot的优势
- 快速搭建:通过 Spring Initializr 或者 Maven 等工具可以快速搭建 Spring Boot 项目,减少繁琐的配置。
- 嵌入式服务器:内置了 Tomcat、Jetty 等服务器,无需单独部署服务器。
- 自动配置:根据项目依赖自动配置 Spring 应用,减少开发人员的配置工作量。
- 生产就绪:提供了生产级别的功能,如健康检查、指标监控等。
二、SpringBoot项目搭建
2.1 使用 Spring Initializr 搭建项目
- 打开 Spring Initializr 网站。
- 在
Project中选择Maven Project。 - 在
Language中选择Java。 - 配置
Group和Artifact等基本信息。 - 在
Dependencies中添加所需的依赖,如Spring Web用于开发 Web 应用。 - 点击
Generate按钮下载项目压缩包。 - 解压项目压缩包,使用 IDE(如 IntelliJ IDEA 或 Eclipse)导入项目。
2.2 使用 Maven 手动搭建项目
- 创建一个 Maven 项目,在
pom.xml中添加 Spring Boot 父依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
- 添加所需的依赖,例如添加
Spring Web依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 创建主应用类,添加
@SpringBootApplication注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
三、SpringBoot自动配置原理
3.1 @SpringBootApplication 注解
@SpringBootApplication 是一个组合注解,包含了 @SpringBootConfiguration、@EnableAutoConfiguration 和 @ComponentScan 三个注解。
@SpringBootConfiguration:本质上就是@Configuration注解,用于标识该类为配置类。@EnableAutoConfiguration:开启自动配置功能,Spring Boot 会根据项目依赖自动配置 Spring 应用。@ComponentScan:自动扫描并注册@Component、@Service、@Repository等注解标注的类。
3.2 自动配置的实现机制
Spring Boot 的自动配置是基于 spring.factories 文件实现的。在 spring-boot-autoconfigure 模块的 META - INF 目录下有一个 spring.factories 文件,该文件中定义了一系列自动配置类。当 Spring Boot 启动时,会根据 @EnableAutoConfiguration 注解加载这些自动配置类,并根据条件判断是否进行配置。
例如,当项目中添加了 spring-boot-starter-web 依赖时,Spring Boot 会自动配置 DispatcherServlet 等 Web 相关的组件。
四、SpringBoot配置文件
4.1 配置文件类型
Spring Boot 支持 application.properties 和 application.yml 两种配置文件类型。
4.1.1 application.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
4.1.2 application.yml
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
4.2 配置文件加载顺序
Spring Boot 会按照以下顺序加载配置文件:
- 命令行参数
SPRING_APPLICATION_JSON中的属性ServletConfig初始化参数ServletContext初始化参数- JNDI 属性(
java:comp/env) - Java 系统属性(
System.getProperties()) - 操作系统环境变量
RandomValuePropertySource中的随机属性- 位于
config目录下的配置文件 - 位于项目根目录下的配置文件
- 位于类路径
config包下的配置文件 - 位于类路径根目录下的配置文件
4.3 自定义配置属性
可以通过 @ConfigurationProperties 注解将配置文件中的属性绑定到 Java 类中。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfigProperties {
private String name;
private int age;
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
在 application.properties 中配置:
myconfig.name=John
myconfig.age=30
五、SpringBoot Web开发
5.1 创建 RESTful 接口
使用 @RestController 注解创建 RESTful 接口。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}
5.2 处理请求参数
可以通过 @RequestParam、@PathVariable 等注解处理请求参数。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ParamController {
@GetMapping("/params")
public String getParams(@RequestParam("name") String name, @RequestParam("age") int age) {
return "Name: " + name + ", Age: " + age;
}
@GetMapping("/path/{id}")
public String getPath(@PathVariable("id") int id) {
return "ID: " + id;
}
}
5.3 异常处理
使用 @ControllerAdvice 和 @ExceptionHandler 注解进行全局异常处理。
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return new ResponseEntity<>("Error: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
六、SpringBoot数据库访问
6.1 使用 Spring Data JPA
Spring Data JPA 是 Spring 提供的用于简化 JPA 开发的框架。
- 添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 配置数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
- 创建实体类:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
// getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- 创建 Repository 接口:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
6.2 使用 MyBatis
MyBatis 是一个优秀的持久层框架。
- 添加依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 配置数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
- 创建实体类和 Mapper 接口:
public class User {
private Long id;
private String name;
private int age;
// getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> getAllUsers();
}
七、SpringBoot测试
7.1 单元测试
使用 JUnit 和 Spring Boot Test 进行单元测试。
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testGetUserById() {
User user = userService.getUserById(1L);
assertEquals("John", user.getName());
}
}
7.2 集成测试
使用 @WebMvcTest 进行 Web 层的集成测试。
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Spring Boot!"));
}
}
八、SpringBoot部署与监控
8.1 部署方式
- jar 包部署:Spring Boot 项目可以打包成可执行的 jar 包,通过
java -jar命令运行。
java -jar myspringbootapp.jar
- Docker 容器部署:将 Spring Boot 项目打包成 Docker 镜像,然后在 Docker 容器中运行。
8.2 监控与管理
Spring Boot Actuator 提供了生产级别的功能,如健康检查、指标监控等。
- 添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 配置 Actuator 端点:
management.endpoints.web.exposure.include=*
- 访问端点:
- 健康检查:
http://localhost:8080/actuator/health - 指标监控:
http://localhost:8080/actuator/metrics

7万+

被折叠的 条评论
为什么被折叠?



