官术网_书友最值得收藏!

How to do it...

  1. 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") }
  1. 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.
  2. 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); 
  } 
} 
  1. Start the application by running ./gradlew clean bootRun.
  2. After the application has started, open the browser and go to http://localhost:8080/books and you should see a response: [].
主站蜘蛛池模板: 谢通门县| 西宁市| 呼伦贝尔市| 石城县| 临猗县| 贵州省| 通江县| 鲁山县| 繁昌县| 西宁市| 万山特区| 永丰县| 墨脱县| 禹州市| 海盐县| 北海市| 库尔勒市| 鹤峰县| 凉城县| 岳阳县| 莲花县| 堆龙德庆县| 黑河市| 沂源县| 罗甸县| 晴隆县| 汝南县| 乐至县| 通海县| 泰来县| 舒兰市| 安远县| 舞钢市| 富阳市| 汪清县| 治多县| 安达市| 平江县| 普兰县| 惠州市| 宁阳县|