springboot起步

2019-04-18  本文已影响0人  错过_16e3

1.创建好新项目后,配置pom文件,添加好必要的依赖

  <properties>
        <project.build.sourseEncoding>UTF-8</project.build.sourseEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.编写实体类Book

package com.springboot.quickstart.entity;

public class Book {
    private Integer id;
    private String name;
    private Double price;

    public Book(Integer id, String name, Double price) {
        this.id = id;
        this.name = name;
        this.price = 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() {
        super();
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

3.写接口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;

/*
 * 图书的DAO类
 * */
@Component
public class BookDAO {
    public List<Book> getBooks(){
        List<Book> books=new ArrayList<>();
        books.add(new Book(1,"Spring Boot实战",88.8));
        books.add(new Book(1,"Spring MVC",98.8));
        books.add(new Book(1,"JAVA从入门到精通",68.8));
        return books;
    }
}

4.编写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 {
//    注入一个bookDao实例
    @Resource
    private BookDAO bookDao;

    @RequestMapping(value = "/books",method = RequestMethod.GET)

    public List<Book> getBooks(){
        return bookDao.getBooks();
    }

}

5.运行springboot启动主类

image

6.用postman测试

image
上一篇下一篇

猜你喜欢

热点阅读