基于Spring Boot實現學生新增。
1. 創建Spring Boot項目
創建Spring Boot項目,項目名稱為case16-springboot-student01。
?
2. 設置項目信息
?
3. 選擇依賴
-
選擇Lombok
?
-
選擇Spring Web
?
4. 設置項目名稱
?
5. Maven依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.11</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.wfit</groupId><artifactId>boot</artifactId><version>0.0.1-SNAPSHOT</version><name>boot</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>
6. 創建配置文件
resources目錄下創建application.yml。
# 配置端口號
server:port: 8090
7. 創建Student實體類
com.wfit.boot.model目錄下創建Student.java。
@Data
public class Student {//主鍵idprivate String id;//姓名private String name;//年齡private int age;
}
8. 創建StudentController類
com.wfit.boot.controller目錄下創建StudentController.java。
@RestController
@RequestMapping("/student")
public class StudentController {@AutowiredStudentService studentService;/*** 新增學生信息*/@PostMapping("/add")public String add(@RequestBody Student student){studentService.addStudent(student);return "success";}
}
9. 創建StudentService接口
com.wfit.boot.service目錄下創建StudentService.java。
public interface StudentService {public int addStudent(Student student);
}
10. 創建StudentServiceImpl類
com.wfit.boot.service.impl目錄下創建StudentServiceImpl.java。
@Service
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentDao studentDao;@Overridepublic void addStudent(Student student) {studentDao.save(student);}
}
11. 創建StudentDao類
com.wfit.boot.dao目錄下創建StudentDao.java。
@Repository
public class StudentDao {public void save(Student student){System.out.println("新增學生信息成功:" + student);}}