Spring Boot . 2 -- 用Spring Boot 創建一個Java Web 應用


  • 通過 start.spring.io 創建工程
  • 通過 IDEA 創建工程

     🌰《Spring Boot In Action》 中的例子

     建立一個展示閱讀列表的應用。不同的用戶將讀過的書的數據登記進來,每次進到頁面都能看到相應的讀書記錄。

     1. 首先登錄頁面 start.spring.io。

     頁面大概長這個樣子:

     點擊空框內的鏈接,會展示更全面的參數選擇。【參數填好后】,選擇 “Generate Project” 就可以將一個完整的Spring Boot 工程下載下來了。

     工程的目錄是這樣的:

     

      pom.xml 是工程構建的明細、ReadingListApplication.java 是bootstrap類 也是Sping 的首要配置類、application.properties 是Spring Boot 和應用讀取特定屬性的文件;在test目錄下 的ReadinglistApplicationTests.java 的就是最基本的測試類。 

BOOTSTRAPING SPRING

     類ReadingListApplication充當了兩個角色:配置Spring,啟動Spring。雖然Spring Boot 負責了幾乎所有的配置任務,但是總要有個入口來告訴Spring Boot 開始進行 AUTO-CONFIGURE,在ReadingListApplication.java 中有一些注解就是喚起自動配置:

@SpringBootApplication  // 就是這個注解喚起自動配置
public class ReadinglistApplication {

    public static void main(String[] args) {
        SpringApplication.run(ReadinglistApplication.class, args);
    }
}

    @SpringBootApplication 觸發了 Component-Scanning 和 自動配置。實際上這個注解做了其他三個注解做的事兒。

  1. @Configuration 等價於在XML中配置了Beans。這個是基於Java的配置。
  2. @ComponentScan。相當於啟動了 Component scanning,其他標記@Controller和@Component的類可以在Spring的Context中被發現和注冊。
  3. @EnableAutoConfiguration 。這個注解本身就是Spring Boot 開啟自動配置的。

     那么問題來了,怎么啟動這個應用呢?最簡單的辦法大概就是 在IDEA中直接右鍵->Run main(). 當然還有CLI的、war 形式的。這些后續慢慢寫。

     現在開發一個簡單的 ReadingListApplication了。需要定義一個Book類表示讀過的書、一個Repository來存儲讀書記錄、一個Controller相應Http請求、一個頁面承接用戶的操作。其他的就不需要了。那這些代碼這么來寫就好了。

     Book.java

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String reader;
    private String isbn;
    private String title;
    private String author;
    private String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getReader() {
        return reader;
    }

    public void setReader(String reader) {
        this.reader = reader;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
View Code

    ReadingListRepository.java

package readinglist;

/**
 * Created on 17/1/4.
 */

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ReadingListRepository extends JpaRepository<Book, Long> {
    List<Book> findByReader(String reader);
}
View Code

     ReadingListController.java

package readinglist;

/**
 * Created on 17/1/4.
 */

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
@ConfigurationProperties(prefix = "amazon")
public class ReadingListController {

    Logger logger = LoggerFactory.getLogger(ReadingListController.class);
    private ReadingListRepository readingListRepository;

    private String associateId;

    @Autowired
    public ReadingListController(ReadingListRepository readingListRepository) {
        this.readingListRepository = readingListRepository;
    }

    @RequestMapping(value = "/{reader}", method = RequestMethod.GET)
    public String getReadingList(@PathVariable("reader") String reader, Model model) {

        List<Book> bookList = readingListRepository.findByReader(reader);

        if (null != bookList) {
            model.addAttribute("books", bookList);
        }

        logger.warn("Here IS Log Output. AssociateId is {}.",associateId);

        return "readingList";
    }

    @RequestMapping(value = "/{reader}", method = RequestMethod.POST)
    public String addToReadingList(@PathVariable("reader") String reader, Book book) {
        book.setReader(reader);
        readingListRepository.save(book);
        return "redirect:/{reader}";
    }

    public void setAssociateId(String associateId) {
        this.associateId = associateId;
    }
}
View Code

     readlingList.html

<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>Reading List</title>
    <link rel="stylesheet" th:href="@{/style.css}" />
</head>
<body>
<h2>Your Reading List</h2>

<div th:unless="${#lists.isEmpty(books)}">
    <dl th:each="book : ${books}">
        <dt class="bookHeadline">
            <span th:text="${book.title}">Title</span> by
            <span th:text="${book.author}">Author</span>
            (ISBN: <span th:text="${book.isbn}">ISBN</span>)
        </dt>
        <dd class="bookDescription">
          <span th:if="${book.description}"
                th:text="${book.description}">Description</span>
          <span th:if="${book.description eq null}">
                No description available</span>
        </dd>
    </dl>
</div>
<div th:if="${#lists.isEmpty(books)}">
    <p>You have no books in your book list</p>
</div>
<hr/>
<h3>Add a book</h3>

<form method="POST">
    <label for="title">Title:</label>
    <input type="text" name="title" size="50"></input><br/>
    <label for="author">Author:</label>
    <input type="text" name="author" size="50"></input><br/>
    <label for="isbn">ISBN:</label>
    <input type="text" name="isbn" size="15"></input><br/>
    <label for="description">Description:</label><br/>
        <textarea name="description" cols="80" rows="5">
        </textarea><br/>
    <input type="submit"></input>
</form>
</body>
</html>
View Code

 

啟動即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM