1.前期项目建立及配置
-
Create New Project ---> Spring Initializr --->Next
-
填写Group 、Artifact (其他默认) --->Next
-
Spring Boot 选择2.1.3(稳定版,其他暂时默认)---> Next
填写项目名(注意路径一致)---> Finish
- pom.xml添加配置(注意添加位置)
<!--字符编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
-
建立文件夹 如图:
2.起步练习
2.1entity (Book 类)
package com.springboot.quickstart.entity;
public class Book {
private Integer id ;
private String name;
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Book(Integer id, String name, Double price) {
this.id = id;
this.name = name;
this.price = price;
}
public Book() {
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
2.2 dao (BookDAO)
package com.springboot.quickstart.dao;
import com.springboot.quickstart.entity.Book;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class BookDAO {
public List<Book> getBook(){
List<Book> books = new ArrayList<>();
books.add(new Book(1, "SpringBoot实战", 88.7));
books.add(new Book(2, "SpringMVC", 98.7));
books.add(new Book(3, "Spring", 80.7));
books.add(new Book(4, "SpringBoot", 100.2));
return books;
}
}
2.3 Controller (BookController)
package com.springboot.quickstart.controller;
import com.springboot.quickstart.dao.BookDAO;
import com.springboot.quickstart.entity.Book;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
public class BookController {
@Resource
private BookDAO bookDAO;
@RequestMapping(value = "/books", method = RequestMethod.GET)
public List<Book> getBooks() {
return bookDAO.getBook();
}
}
2.4 Postman运行