哪里有微信网站建设,整合营销网站建设,美食烹饪网站策划书,搜索推广是什么一、Spring Boot 简介 Spring Boot 是一个用于创建独立的、基于 Spring 的生产级应用程序的框架。它简化了 Spring 应用的初始搭建和开发过程#xff0c;通过自动配置等功能#xff0c;让开发者能够快速地构建应用#xff0c;减少了大量的样板代码和复杂的配置。
二、核心特…一、Spring Boot 简介 Spring Boot 是一个用于创建独立的、基于 Spring 的生产级应用程序的框架。它简化了 Spring 应用的初始搭建和开发过程通过自动配置等功能让开发者能够快速地构建应用减少了大量的样板代码和复杂的配置。
二、核心特性
一自动配置 原理 Spring Boot 根据类路径中的依赖自动配置 Spring 应用上下文。它使用条件注解如ConditionalOnClass、ConditionalOnMissingBean等来决定是否需要配置某个组件。例如如果spring - boot - starter - web在类路径中并且没有自定义的Servlet相关配置Spring Boot 会自动配置一个嵌入式的 Web 服务器如 Tomcat并配置好Spring MVC的相关组件。优点 极大地减少了手动配置的工作量。以前在 Spring 应用中需要手动配置很多组件如数据源、事务管理器等而在 Spring Boot 中只要添加相应的依赖就可以自动完成大部分配置。
二起步依赖Starter Dependencies 概念 Spring Boot 提供了一系列的 “starter” 依赖这些依赖将常用的功能相关的库整合在一起。例如spring - boot - starter - web包含了构建 Web 应用所需的 Spring MVC、嵌入式 Web 服务器等相关依赖。开发者只需要在pom.xmlMaven 项目或build.gradleGradle 项目中添加所需的 starter 依赖就可以快速引入功能而无需关心具体需要哪些库。使用示例 在pom.xml中添加spring - boot - starter - data - jpa依赖就可以在项目中方便地使用 JPAJava Persistence API进行数据库访问无需手动添加 Hibernate 等相关依赖。
三内置服务器 Spring Boot 默认支持嵌入式的 Web 服务器如 Tomcat、Jetty 或 Undertow。可以在application.properties或application.yml中轻松配置服务器的端口、上下文路径等属性。例如server.port 8080可以设置应用运行的端口。
三、配置文件
一两种格式 application.properties 这是一种传统的键值对形式的配置文件。例如spring.datasource.url jdbc:mysql://localhost:3306/mydb用于配置数据源的 URL。application.yml或 application.yaml 这是一种更具可读性的、基于 YAML 语法的配置文件具有层次结构。例如
yaml
spring:datasource:url: jdbc:mysql://localhost:3306/mydb二属性注入 Value 注解 可以将配置文件中的属性值注入到 Java 类的字段中。例如
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;Component
public class MyConfig {Value(${myapp.name})private String appName;// 可以在类的其他方法中使用 appName
}ConfigurationProperties 注解 用于将配置文件中的一组相关属性绑定到一个 Java 类上。例如配置文件中有以下内容
myapp:database:host: localhostport: 3306username: rootpassword: password可以创建一个 Java 类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;Component
ConfigurationProperties(myapp.database)
public class DatabaseConfig {private String host;private int port;private String username;private String password;// 生成相应的getter和setter方法
}四、Web 开发
一创建 RESTful API 使用 RestController 注解RestController是一个组合了Controller和ResponseBody功能的注解。在一个被RestController标注的类中可以使用GetMapping、PostMapping、PutMapping、DeleteMapping等注解来处理不同类型的 HTTP 请求。例如
import org.springframework.web.bind.annotation.*;RestController
public class UserController {GetMapping(/users)public ListUser getUsers() {// 返回用户列表的逻辑return userService.getUsers();}PostMapping(/users)public User createUser(RequestBody User user) {// 创建用户的逻辑return userService.createUser(user);}
}处理请求参数 RequestParam用于获取 URL 中的查询参数。例如/users?id1可以在方法中使用RequestParam(id) Integer id来获取参数值。PathVariable用于获取 URL 路径中的参数。例如/users/{id}可以在方法中使用PathVariable(id) Integer id来获取参数值。
二视图模板可选 如果需要开发传统的 Web 页面可以集成视图模板引擎如 Thymeleaf、FreeMarker 等。以 Thymeleaf 为例需要在pom.xml中添加spring - boot - starter - thymeleaf依赖然后在src/main/resources/templates目录下创建 HTML 模板文件在模板文件中可以使用 Thymeleaf 的语法来绑定数据和进行逻辑判断等。
五、数据库访问
一JPAJava Persistence API 实体类定义 使用Entity注解标记一个 Java 类为实体类表示它与数据库中的表对应。例如
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;Entity
public class User {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id;private String name;private String email;// 生成相应的getter和setter方法
}数据访问接口 可以通过继承JpaRepository接口来实现基本的数据库操作。例如
import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepositoryUser, Long {// 可以在这里定义自定义的查询方法可选
}二数据库连接配置 在application.properties或application.yml中配置数据库连接信息包括 URL、用户名、密码、驱动等。例如对于 MySQL 数据库
properties
spring.datasource.url jdbc:mysql://localhost:3306/mydb
spring.datasource.username root
spring.datasource.password password
spring.datasource.driver - class - name com.mysql.cdriver六、测试
一单元测试 使用 JUnit 等测试框架结合 Spring Boot 的测试支持进行单元测试。可以使用SpringBootTest注解启动整个 Spring 应用上下文使用MockBean注解模拟依赖的组件。例如
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import static org.mockito.Mockito.*;SpringBootTest
public class UserServiceTest {Autowiredprivate UserService userService;MockBeanprivate UserRepository userRepository;Testpublic void testGetUsers() {when(userRepository.findAll()).thenReturn(Arrays.asList(new User()));ListUser users userService.getUsers();assertEquals(1, users.size());verify(userRepository, times(1)).findAll();}
}二集成测试 通过SpringBootTest注解启动整个应用测试不同组件之间的交互。例如测试UserController与UserService之间的数据传递和业务逻辑执行是否正确。
七、实际用例简单的员工管理系统
一需求分析 实现一个简单的员工管理系统能够进行员工信息的查询、添加、更新和删除操作。提供 RESTful API 供前端应用或其他后端服务调用。将员工信息存储在数据库中。
二技术选型 使用 Spring Boot 构建后端应用。使用 MySQL 数据库存储数据。使用 Spring Data JPA 进行数据库访问。构建 RESTful API 使用RestController和相关的请求映射注解。
三实现步骤 创建 Spring Boot 项目 使用 Spring Initializr 创建一个新的 Spring Boot 项目添加spring - boot - starter - web和spring - boot - starter - data - jpa依赖以及 MySQL 数据库驱动依赖。定义实体类
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;Entity
public class Employee {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id;private String name;private String department;private double salary;// 生成getter和setter方法
}创建数据访问接口
import org.springframework.data.jpa.repository.JpaRepository;public interface EmployeeRepository extends JpaRepositoryEmployee, Long {
}创建服务层
import org.springframework.stereotype.Service;
import java.util.List;Service
public class EmployeeService {private final EmployeeRepository employeeRepository;public EmployeeService(EmployeeRepository employeeRepository) {this.employeeRepository employeeRepository;}public ListEmployee getEmployees() {return employeeRepository.findAll();}public Employee getEmployeeById(Long id) {return employeeRepository.findById(id).orElse(null);}public Employee saveEmployee(Employee employee) {return employeeRepository.save(employee);}public void deleteEmployee(Long id) {employeeRepository.deleteById(id);}
}创建控制器
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;RestController
RequestMapping(/employees)
public class EmployeeController {private final EmployeeService employeeService;public EmployeeController(EmployeeService employeeService) {this.employeeService employeeService;}GetMappingpublic ResponseEntityListEmployee getEmployees() {ListEmployee employees employeeService.getEmployees();return new ResponseEntity(employees, HttpStatus.OK);}GetMapping(/{id})public ResponseEntityEmployee getEmployeeById(PathVariable Long id) {Employee employee employeeService.getEmployeeById(id);if (employee! null) {return new ResponseEntity(employee, HttpStatus.OK);}return new ResponseEntity(HttpStatus.NOT_FOUND);}PostMappingpublic ResponseEntityEmployee createEmployee(RequestBody Employee employee) {Employee savedEmployee employeeService.saveEmployee(employee);return new ResponseEntity(savedEmployee, HttpStatus.CREATED);}PutMapping(/{id})public ResponseEntityEmployee updateEmployee(PathVariable Long id, RequestBody Employee employee) {if (employeeService.getEmployeeById(id)! null) {employee.setId(id);Employee updatedEmployee employeeService.saveEmployee(employee);return new ResponseEntity(updatedEmployee, HttpStatus.OK);}return new ResponseEntity(HttpStatus.NOT_FOUND);}DeleteMapping(/{id})public ResponseEntityVoid deleteEmployee(PathVariable Long id) {if (employeeService.getEmployeeById(id)! null) {employeeService.deleteEmployee(id);return new ResponseEntity(HttpStatus.NO_CONTENT);}return new ResponseEntity(HttpStatus.NOT_FOUND);}
}配置数据库连接 在application.properties中配置 MySQL 数据库连接信息
spring.datasource.url jdbc:mysql://localhost:3306/companydb
spring.datasource.username root
spring.datasource.password password
spring.datasource.driver - class - name com.mysql.cdriver测试应用 可以使用 Postman 等工具来测试创建的 RESTful API。例如发送 GET 请求到/employees可以获取所有员工信息发送 POST 请求到/employees并在请求体中包含员工信息可以创建新员工等。同时可以编写单元测试和集成测试来确保各个组件的功能正确性。