基于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 {
//主键id
private String id;
//姓名
private String name;
//年龄
private int age;
}
8. 创建StudentController类
com.wfit.boot.controller目录下创建StudentController.java。
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentService 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 {
@Autowired
private StudentDao studentDao;
@Override
public 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);
}
}