第四天学习内容安排
1. 复习第三天的内容
- 基本项目结构:复习 Spring Boot 项目的基本结构和配置文件。
- 依赖注入:回顾 Spring Boot 中的依赖注入(DI)和控制反转(IoC)概念。
2. Spring Boot 的配置
-
application.properties / application.yml:
- 学习如何使用
application.properties
或application.yml
文件进行配置。
server.port=8081 spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password
- 学习如何使用
-
自定义配置:
- 学习如何创建自定义配置类:
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "app") public class AppConfig { private String name; private String version; // Getters and Setters }
3. 数据库访问
-
Spring Data JPA:
- 学习如何使用 Spring Data JPA 进行数据库操作。
- 添加依赖到
pom.xml
:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
-
创建实体类:
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 String email; // Getters and Setters }
-
创建 Repository 接口:
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { User findByEmail(String email); }
4. 创建 RESTful API
- 使用 @RestController:
- 学习如何创建 RESTful API:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public List<User> getAllUsers() { return userRepository.findAll(); } @PostMapping public User createUser(@RequestBody User user) { return userRepository.save(user); } }
5. 处理异常
- 全局异常处理:
- 学习如何使用
@ControllerAdvice
进行全局异常处理:
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<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
- 学习如何使用
6. 实践练习
- 创建一个简单的 Spring Boot 应用,包含用户实体和基本的 CRUD 操作。
- 使用 Spring Data JPA 进行数据库操作,创建 RESTful API。
- 实现全局异常处理,确保应用能够优雅地处理错误。