Spring Boot入門

SpringBoot入門

1. SpringBoot簡介

spring boot是一種全新的Java web框架,目的是簡化Spring應用的初始搭建和開發(fā)過程,讓開發(fā)者寫更少的配置,程序更快的啟動和運行,致力于成為快速開發(fā)應用領(lǐng)域的領(lǐng)導者。

從它的名字也可以看出,更像是一個引導程序,就跟我們傻瓜式的安裝電腦軟件一樣,next,next...很快我們就可以搭建起一個Spring應用。

2. Spring產(chǎn)生背景

在使用Spring和Spring MVC框架的時候,我們需要手動配置很多東西,我們更希望的是“約定大于配置”,就是說系統(tǒng)、類庫、框架應該假定合理的默認值,而非要求提供不必要的配置,使用Spring和Spring MVC進行很多配置,不僅增加了工作量,而且在跨平臺部署的時候容易出現(xiàn)問題。由于這些問題的存在,Spring Boot應運而生,使用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配置??偟膩碚f,Spring Boot大致有以下優(yōu)缺點。

優(yōu)點:

  1. Spring Boot使編碼變簡單;
  2. Spring Boot使配置變簡單;
  3. Spring Boot使部署變簡單;
  4. Spring Boot使監(jiān)控變簡單;

缺點:

  1. 缺少注冊、服務發(fā)現(xiàn)等外圍方案;
  2. 缺少外圍監(jiān)控集成方案;
  3. 缺少外圍安全管理方案;
  4. 缺少REST落地的URI規(guī)劃方案;
  5. 比較適合做微服務,不太適合比較大型的項目;
  6. 集成度較高,使用過程中不太容易了解底層。

Spring Boot只是微服務框架的起點,配合Spring Cloud可以快速搭建微服務。

4. 搭建一個簡單的Spring Boot工程

  1. 新建一個maven工程;

  2. 在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>
    
  3. 在App.java中編寫服務,這是是程序的入口,通過簡單的注釋就可以發(fā)布一個服務。

    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);
     }
    }
    
  4. 然后點擊運行,可以在控制臺看到輸出了Spring Boot字樣:

    
         .   ____          _            __ _ _
        /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
       ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
        \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
         '  |____| .__|_| |_|_| |_\__, | / / / /
        =========|_|==============|___/=/_/_/_/
        :: Spring Boot ::        (v2.0.2.RELEASE)
    

    運行成功后會顯示:

    Tomcat started on port(s): 8080 (http) with context path
    

    ?

  5. 在瀏覽器打開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);
}

重新啟動服務,然后可以在postman中,重新模擬發(fā)送post請求。

6. 遇到的問題

1. spring boot發(fā)布的post服務報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)上搜了一波,原來是在實體類中導入的Id類的包不對,之前導入的是:

import org.springframework.data.annotation.Id;

應該是:

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

https://blog.csdn.net/u012702547/article/details/53740047

https://blog.csdn.net/forezp/article/details/61472783

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容