Spring Boot的特點以及簡單使用
阿新 • • 發佈:2020-12-15
技術標籤:Spring Bootspringjavaspring bootmavenmybatis
前言:
Spring Boot 是一個快速開發框架,它開啟了各種自動裝配,從而簡化程式碼的編寫,不需要編寫各種配置檔案,只需要引入相關依賴和註解就可以迅速搭建一個應用。
Spring Boot的特點:
- 不需要配置web.xml
- 不需要配置 springmvc.xml
- 不需要 Tomcat,因為Spring Boot 內部整合了 tomcat 相當於已經為你部署好了不需要你在配置Tomcat
- 不需要配置 JSON 解析,支援 REST 架構
對於每個人的理解不同可能還有其它方面的特點這裡就不在概述。
Spring Boot的使用
1、建立 Maven 工程,匯入相關依賴。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
</parent>
<dependencies>
<!-- web包 -->
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
</dependencies>
如果不知道從哪裡匯入相關依賴,可以去spring boot官網查詢。
2、建立Student
實體類
public class Student {
private long id;
private String name;
private int age;
}
3、建立StudentRepository
介面
public interface StudentRepository {
public Collection<Student> findAll();
public Student findById(long id);
public void saveOrUpdate(Student student);
public void deleteById(long id);
}
4、建立StudentRepositoryImpl
繼承StudentRepository
@Repository
public class StudentRepositoryImpl implements StudentRepository {
private static Map<Long,Student> studentMap;
static{
studentMap = new HashMap<>();
studentMap.put(1,new Student(1,"張三",15));
studentMap.put(2,new Student(2,"李四",18));
studentMap.put(3,new Student(3,"王五",17));
}
@Override
public Collection<Student> findAll() {
return studentMap.values();
}
@Override
public Student findById(long id) {
return studentMap.get(id);
}
@Override
public void saveOrUpdate(Student student) {
studentMap.put(student.getId(),student);
}
@Override
public void deleteById(long id) {
studentMap.remove(id);
}
}
注意:繼承一個類需要重寫該類的所有方法
5、StudentHandler
@RestController
@RequestMapping("/student")
public class StudentHandler {
@Autowired
private StudentRepository studentRepository;
@GetMapping("/findAll")
public Collection<Student> findAll(){
return studentRepository.findAll();
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id") long id){
return studentRepository.findById(id);
}
@PostMapping("/save")
public void save(@RequestBody Student student){
studentRepository.saveOrUpdate(student);
}
@PutMapping("/update")
public void update(@RequestBody Student student){
studentRepository.saveOrUpdate(student);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") long id){
studentRepository.deleteById(id);
}
}
6、application.yml
server:
port: 8081
埠號可以隨意配置
7、主類
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
@SpringBootApplication 表示當前類是主類而啟動主類只需要使用SpringApplication.run(Application.class,args);即可