SpringBoot入門
1. SpringBoot簡介
spring boot是一種全新的Java web框架,目的是簡化Spring應(yīng)用的初始搭建和開發(fā)過程,讓開發(fā)者寫更少的配置,程序更快的啟動和運行,致力于成為快速開發(fā)應(yīng)用領(lǐng)域的領(lǐng)導(dǎo)者。
從它的名字也可以看出,更像是一個引導(dǎo)程序,就跟我們傻瓜式的安裝電腦軟件一樣,next,next...很快我們就可以搭建起一個Spring應(yīng)用。
2. Spring產(chǎn)生背景
在使用Spring和Spring MVC框架的時候,我們需要手動配置很多東西,我們更希望的是“約定大于配置”,就是說系統(tǒng)、類庫、框架應(yīng)該假定合理的默認(rèn)值,而非要求提供不必要的配置,使用Spring和Spring MVC進行很多配置,不僅增加了工作量,而且在跨平臺部署的時候容易出現(xiàn)問題。由于這些問題的存在,Spring Boot應(yīng)運而生,使用Spring Boot我們可以很快的創(chuàng)建一個基于Spring的項目,讓這個Spring項目跑起來只需要很少的配置就可以了。
3. Spring Boot的優(yōu)缺點
Spring Boot可以獨立運行Spring項目,它可以以jar包的形式來運行,java -jar xxx.jar
就可以運行,很方便。并且可以內(nèi)嵌Tomcat,這樣我們無需以war包的形式部署項目。Spring Boot通過starter能夠幫助我們簡化maven配置。總的來說,Spring Boot大致有以下優(yōu)缺點。
優(yōu)點:
- Spring Boot使編碼變簡單;
- Spring Boot使配置變簡單;
- Spring Boot使部署變簡單;
- Spring Boot使監(jiān)控變簡單;
缺點:
- 缺少注冊、服務(wù)發(fā)現(xiàn)等外圍方案;
- 缺少外圍監(jiān)控集成方案;
- 缺少外圍安全管理方案;
- 缺少REST落地的URI規(guī)劃方案;
- 比較適合做微服務(wù),不太適合比較大型的項目;
- 集成度較高,使用過程中不太容易了解底層。
Spring Boot只是微服務(wù)框架的起點,配合Spring Cloud可以快速搭建微服務(wù)。
4. 搭建一個簡單的Spring Boot工程
新建一個maven工程;
-
在pom文件中添加spring boot的依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> </parent> ... <dependencies> ... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
-
在App.java中編寫服務(wù),這是是程序的入口,通過簡單的注釋就可以發(fā)布一個服務(wù)。
package com.wangjun.spring.springboottest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @EnableAutoConfiguration public class App { @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } @RequestMapping("/name") @ResponseBody String getName() { return "spring boot test"; } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
-
然后點擊運行,可以在控制臺看到輸出了Spring Boot字樣:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.2.RELEASE)
運行成功后會顯示:
Tomcat started on port(s): 8080 (http) with context path
?
在瀏覽器打開localhost:8080,可以看到頁面返回Hello World! 打開localhost:8080/name,可以看到頁面返回spring boot test。
OK。就是這么簡單!spring boot內(nèi)置了servlet容器,所以不需要想傳統(tǒng)方式那樣,先部署到容器再啟動容器,只需要運行main函數(shù)即可。
配置yml文件:在Java的路徑下新建resources文件夾,里面新建application.yml文件,在eclipse中將recourse文件夾設(shè)置為Source Folder。
在yml里面寫一點配置:
server:
port: 8030
你還需要在pom文件中添加依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
因為spring-boot-starter會自動加載yml文件(application.yml)
接下來重新啟動,訪問端口就變成了8030。
5. 使用jpa操作數(shù)據(jù)庫
在pom中添加依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
在appilication.yml中添加數(shù)據(jù)庫配置:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT
username: root
password: password
jpa:
hibernate:
ddl-auto: create #create 代表在數(shù)據(jù)庫創(chuàng)建表,update 代表更新
show-sql: true
創(chuàng)建一個實體:
package com.wangjun.spring.springboottest;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy= GenerationType.AUTO) //和表的id生成策略相同
//id要使用javax.persistence下面的,必然會報錯No identifier specified for entity
private Integer id;
private String name;
private Integer age;
public User() {
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
創(chuàng)建Dao接口, springboot 將接口類會自動注解到spring容器中,不需要我嗎做任何配置,只需要繼承JpaRepository 即可:
package com.wangjun.spring.springboottest;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRep extends JpaRepository<User, Integer>{
}
創(chuàng)建User的controller類,添加查詢和添加的方法:
package com.wangjun.spring.springboottest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAutoConfiguration
public class UserController {
@Autowired
private UserRep userRep;
@RequestMapping("/users")
@ResponseBody
public List<User> getUserList(){
return userRep.findAll();
}
@RequestMapping("/adduser")
@ResponseBody
public User addUser(@RequestParam("name") String name, @RequestParam("age") Integer age) {
User user = new User();
user.setName(name);
user.setAge(age);
return userRep.save(user);
}
}
主方法中改為:
package com.wangjun.spring.springboottest;
import org.springframework.boot.SpringApplication;
public class App {
public static void main(String[] args) {
SpringApplication.run(UserController.class, args);
}
}
運行程序,通過get方式訪問
http://localhost:8030/users
http://localhost:8030/adduser?name="nike"&age=25
就可以查詢或者刪除數(shù)據(jù)了。
如過想用post請求,只需要在注解中將method的值改為POST:
@RequestMapping(value = "/adduser", method = RequestMethod.POST)
@ResponseBody
public User addUser(@RequestParam("name") String name, @RequestParam("age") Integer age) {
User user = new User();
user.setName(name);
user.setAge(age);
return userRep.save(user);
}
重新啟動服務(wù),然后可以在postman中,重新模擬發(fā)送post請求。
6. 遇到的問題
1. spring boot發(fā)布的post服務(wù)報400錯誤
使用postman發(fā)送請求時,使用raw,里面直接寫json:
{"name":"name", "age":22}
報錯:400 Bad Request。
使用form-data和x-www-form-urlencoded形式發(fā)送數(shù)據(jù)可以正常返回。
解決方案:
addUser(@RequestParam("name") String name, @RequestParam("age") Integer age)
這種形式定義的方法只能接受表單形式的數(shù)據(jù),如果要想接收json數(shù)據(jù),可以將其改為:
@RequestMapping(value = "/adduser", method = RequestMethod.POST)
@ResponseBody
public User addUser(@RequestBody User user) {
return userRep.save(user);
}
2. 啟動時報錯:No identifier specified for entity
錯誤日志:
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.wangjun.spring.springboottest.User
解決方案:
在網(wǎng)上搜了一波,原來是在實體類中導(dǎo)入的Id類的包不對,之前導(dǎo)入的是:
import org.springframework.data.annotation.Id;
應(yīng)該是:
import javax.persistence.Id;
3. 每次重啟項目,數(shù)據(jù)庫數(shù)據(jù)會被清空
解決方案:
在application.yml文件中,修改
ddl-auto: update #create 代表在數(shù)據(jù)庫創(chuàng)建表,update 代表更新
參考:
https://blog.csdn.net/fly_zhyu/article/details/76407830
https://www.zhihu.com/question/39483566