这个系列将开始讲解我们如何使用Spring Boot来高效地编写我们的spring web程序。在这篇文章中,我会简单的介绍什么是Spring Boot 以及如何使用Spring Boot来配置一个简单的应用程序。应用程序代码来源于《Spring Boot 实战》这本书。也可以直接学习Spring boot 中文文档!
话不多说,我们直接来讲什么是Spring Boot。Spring Boot 相比于我们的传统的使用xml或者Java配置的Spring应用,有以下四个核心优点:
1. 自动配置:例如我们之前使用的嵌入式H2数据库,或者我们自己创建的Bean都需要尽心配置。Spring Boot会自动检测Classpath中的我们需要的配置,然后为我们的Bean注入。
2. 起步依赖:这个就是我们的spring-boot-starter-XXX的功劳。还记得我们之前的maven项目中需要用到的那些依赖么?在SpringBoot中,我们只需要设置一个起步依赖,例如spring-boot-starter-web,他会利用依赖传递把其他的依赖引入项目里。
3.命令行界面:Spring Boot CLI。下面我会展示一个CLI的例子。
4.Actuator:提供众多web站点,了解程序运行时的内部情况。后面有文章会介绍。
我们使用CLI写一个最简单的Hello world 来展示Spring Boot 有多么的简洁!
@RestController
class HelloController{
@RequestMapping("/")
public String hello(){
return "hello world";
}
}
这段程序你一定不陌生。就是我们在之前最经常用到的Controller的类。他映射我们的“/”URL,然后打印字符串“hello world”。在我们之前的Spring MVC项目你至少需要这么做:
1. 创建一个maven项目,引入spring framework的相关依赖。
2. 新建web.xml 配置 DispatcherServlet的信息
4. 新建类配置一个应用上下文
3. 新建类配置一个Controller
但是这里,你只需要上述的代码,然后启动你的PowerShell然后 执行 spring run HelloController.java
下面,我们使用Intellij 来创建一个web应用ReadingList,代码来自《Spring Boot 实战》
首先,使用spring-initailzer来创建一个你的Spring Boot 应用:
项目结构是这样的:
创建我们的Book实体:
package com.example;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Created by YanMing on 2017/3/14.
*/
@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 this.id;
}
public void setId(Long id){
this.id = id;
}
public String getReader(){
return this.reader;
}
public void setReader(String reader){
this.reader = reader;
}
public String getIsbn(){
return this.isbn;
}
public void setIsbn(String isbn){
this.isbn = isbn;
}
public String getTitle(){
return this.title;
}
public void setTitle(String title){
this.title = title;
}
public String getAuthor(){
return this.author;
}
public void setAuthor(String author){
this.author = author;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
}
其中@Entity意为这个实体类应该与一个数据库表对应,表的名称可以由类名推断。
@Id注解修饰的属性应该作为表中的主键
@GeneratedValue修饰的属性应该由数据库自动生成
一个继承了Interface JpaRepository<T,ID extends Serializable>的数据库接口:ReadingListRepository
package com.example;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Created by YanMing on 2017/3/14.
*/
public interface ReadingListRepository extends JpaRepository<Book,Long> {
List<Book> findByReader(String reader);
}
Controller 代码很简单 不再解释 不懂得同学可以看前面Spring MVC部分关于RequestMapping的解释
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.util.List;
/**
* Created by YanMing on 2017/3/14.
*/
@Controller
@RequestMapping("/")
public class ReadingListController {
private ReadingListRepository readingListRepository;
@Autowired
public ReadingListController(
ReadingListRepository readingListRepository){
this.readingListRepository = readingListRepository;
}
@RequestMapping(value = "/{reader}",method = RequestMethod.GET)
public String readerBooks(@PathVariable("reader") String reader,Model model)
{
List<Book> readinglist = readingListRepository.findByReader(reader);
if(readinglist != null){
model.addAttribute("books",readinglist);
}
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}";
}
}
这里@PathVariable("reader") String reader 意思就是将URL中的reader作为String 类型的变量传入方法。
在readerBooks方法中,我们将查询到的readinglist作为参数添加到model中,books绑定了readinglist,然后由Thymeleaf渲染出页面。
readinglist.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"/><br/>
<label for="author">Author:</label>
<input type="text" name="author" size="50"/><br/>
<label for="isbn">ISBN:</label>
<input type="text" name="isbn" size="15"/><br/>
<label for="description">Description:</label><br/>
<textarea name="description" cols="80" rows="5">
</textarea><br/>
<input type="submit"/>
</form>
</body>
</html>
关于 thymeleaf 的讲解,点击链接。
最后,我们的启动器如下所示:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
启动后,输入localhost:/8080/1
输入你的信息,点击提交。
注:我在application.propertites中将端口号改为了8000,下载源码的朋友请注意
P.S. 文章不妥之处还望指正