- Spring Boot 2.0 Cookbook(Second Edition)
- Alex Antonov
- 210字
- 2021-06-24 19:24:39
How to do it...
- The very first thing that we will need to do is add a new dependency to build.gradle with the spring-boot-starter-web starter to get us all the necessary libraries for web-based functionality. The following code snippet is what it will look like:
dependencies { compile("org.springframework.boot:spring-boot-starter-data-jpa") compile("org.springframework.boot:spring-boot-starter-jdbc") compile("org.springframework.boot:spring-boot-starter-web") runtime("com.h2database:h2")
runtime("mysql:mysql-connector-java") testCompile("org.springframework.boot:spring-boot-starter-test") }
- Next, we will need to create a Spring controller that will be used to handle the web requests for the catalog data in our application. Let's start by creating a new package structure to house our controllers so that we have our code nicely grouped by its appropriate purposes. Create a package folder called controllers in the src/main/java/com/example/bookpub directory from the root of our project.
- As we will be exposing the book data, let's create the controller class file called BookController in our newly created package with the following content:
@RestController @RequestMapping("/books") public class BookController { @Autowired private BookRepository bookRepository; @RequestMapping(value = "", method = RequestMethod.GET) public Iterable<Book> getAllBooks() { return bookRepository.findAll(); } @RequestMapping(value = "/{isbn}", method = RequestMethod.GET) public Book getBook(@PathVariable String isbn) { return bookRepository.findBookByIsbn(isbn); } }
- Start the application by running ./gradlew clean bootRun.
- After the application has started, open the browser and go to http://localhost:8080/books and you should see a response: [].
推薦閱讀
- Building Computer Vision Projects with OpenCV 4 and C++
- 云計算環(huán)境下的信息資源集成與服務(wù)
- Architects of Intelligence
- 分布式數(shù)據(jù)庫系統(tǒng):大數(shù)據(jù)時代新型數(shù)據(jù)庫技術(shù)(第3版)
- 圖解機(jī)器學(xué)習(xí)算法
- R數(shù)據(jù)科學(xué)實戰(zhàn):工具詳解與案例分析(鮮讀版)
- Access 2016數(shù)據(jù)庫技術(shù)及應(yīng)用
- Lean Mobile App Development
- 區(qū)塊鏈通俗讀本
- 數(shù)據(jù)庫原理與應(yīng)用(Oracle版)
- Power BI商業(yè)數(shù)據(jù)分析完全自學(xué)教程
- Python金融數(shù)據(jù)分析(原書第2版)
- 視覺大數(shù)據(jù)智能分析算法實戰(zhàn)
- 貫通SQL Server 2008數(shù)據(jù)庫系統(tǒng)開發(fā)
- Python數(shù)據(jù)分析從小白到專家