SpringBoot入門一

SpringBoot能夠很簡單的創建一個直接運行的單體Spring應用

特性:

  • 單體Spring應用
  • 內置的tomcat、Jetty
  • 提供默認的starter來構建配置
  • 自動配置Spring和第三方庫

推薦一個很好的學習教程,https://blog.csdn.net/u010486495/article/details/79348302

1 構建hello world工程

MAVEN構建

  • pom.xml

parent、starter、test、web

	<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>

構建一個簡單的hello world工程就遇到了兩個坑,第一個springboot只會掃描啟動類所在包的類和子包的類;

第二個是寫測試類的時候發現@SpringApplicationConfiguration這個注解已經被取消掉了,使用@SpringBootTest這個注解

  • 屬性文件

在src/main/resources目錄創建一個application.properties

  • 定義Controller

package com.didispace.web;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@RequestMapping("/hello")public String index() {return "Hello World";}}
  • 啟動類
package com.didispace;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class Chapter1Application {public static void main(String[] args) {SpringApplication.run(Chapter1Application.class, args);}
}
  • 測試
package com.didispace;import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;import com.didispace.web.HelloController;@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MockServletContext.class)
@WebAppConfiguration
public class Chapter1ApplicationTests {private MockMvc mvc;@Beforepublic void setUp() throws Exception {mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();}@Testpublic void getHello() throws Exception {mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Hello World")));System.out.println("OK");}}

2 屬性、隨機數、多環境配置

屬性文件application.properties

在application.properties中定義隨機數:net.csdn.chapter1.number=${random.int}

多環境配置:在application.properties中定義spring.profiles.active=prod,那么會加載application-prod.properties文件中配置的屬性

3 創建一套簡單的restfulapi,單元測試

  • User.java
package cc.bean;public class User {private Long id;private String name;private Integer age;public Long getId() {return id;}public void setId(Long 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;}}
  • UserController.java
package cc.controller;import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;import cc.bean.User;@RestController
@RequestMapping(path="/users")
public class UserController {static Map<Long,User> userMap = Collections.synchronizedMap(new HashMap<Long,User>());@RequestMapping(path="/",method=RequestMethod.GET)public List<User> getUserList(){List<User> userList = new ArrayList<User>(userMap.values());return userList;}@RequestMapping(path="/",method=RequestMethod.POST)public String addUser(@ModelAttribute User user){userMap.put(user.getId(), user);return "success";}@RequestMapping(path="/{id}",method=RequestMethod.GET)public User getUser(@PathVariable Long id){return userMap.get(id);}@RequestMapping(path="/{id}",method=RequestMethod.PUT)public String addUser(@PathVariable Long id,@ModelAttribute User user){User u = userMap.get(user.getId());u.setName(user.getName());u.setAge(user.getAge());userMap.put(u.getId(), u);return "success";}@RequestMapping(path="/{id}",method=RequestMethod.DELETE)public String delUser(@PathVariable Long id){userMap.remove(id);return "success";}}
  • UserControllerTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;import cc.Chapter2Application;
import cc.controller.UserController;@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Chapter2Application.class)
@WebAppConfiguration
public class UserControllerTest {private MockMvc mvc;@Beforepublic void setUp() {mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();}@Testpublic void testUserController() throws Exception {
//  	測試UserControllerRequestBuilder request = null;// 1、get查一下user列表,應該為空request = get("/users/");mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[]")));// 2、post提交一個userrequest = post("/users/").param("id", "1").param("name", "測試大師").param("age", "20");mvc.perform(request)
//				.andDo(MockMvcResultHandlers.print()).andExpect(content().string(equalTo("success")));// 3、get獲取user列表,應該有剛才插入的數據request = get("/users/");mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"測試大師\",\"age\":20}]")));// 4、put修改id為1的userrequest = put("/users/1").param("name", "測試終極大師").param("age", "30");mvc.perform(request).andExpect(content().string(equalTo("success")));// 5、get一個id為1的userrequest = get("/users/1");mvc.perform(request).andExpect(content().string(equalTo("{\"id\":1,\"name\":\"測試終極大師\",\"age\":30}")));// 6、del刪除id為1的userrequest = delete("/users/1");mvc.perform(request).andExpect(content().string(equalTo("success")));// 7、get查一下user列表,應該為空request = get("/users/");mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[]")));}
}

除了可以用JUNIT做單元測試外,還可以用火狐瀏覽器Rested Client插件發送http請求。

4?springboot-mybatis簡單整合

  • pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>springboot</groupId><artifactId>springboot-mybatis</artifactId><version>0.0.1-SNAPSHOT</version><description>springboot-mybatis整合</description><!-- Spring Boot 啟動父依賴 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.1.RELEASE</version></parent><dependencies><!-- Spring Boot Web 依賴 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Boot Test 依賴 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- 熱交換 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><!-- Spring Boot Mybatis 依賴 --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.2.0</version></dependency><!-- MySQL 連接驅動依賴 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies>
</project>
  • application.properties
## 數據源配置
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=a123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver## Mybatis 配置
mybatis.typeAliasesPackage=org.spring.springboot.domain
mybatis.mapperLocations=classpath:mapper/*.xml
  • CityMapper.xml

mybatis映射文件,在src\main\resources\mapper目錄創建一個CityMapper.xml文件

使用逆向工程生成代碼

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.spring.springboot.dao.CityDao"><resultMap id="BaseResultMap" type="org.spring.springboot.domain.City"><result column="id" property="id" /><result column="province_id" property="provinceId" /><result column="city_name" property="cityName" /><result column="description" property="description" /></resultMap><parameterMap id="City" type="org.spring.springboot.domain.City"/><sql id="Base_Column_List">id, province_id, city_name, description</sql><select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String">select<include refid="Base_Column_List" />from citywhere city_name like '%${cityName}%'</select></mapper>
  • entity、dao、service、controller
package org.spring.springboot.domain;/*** 城市實體類**/
public class City {/*** 城市編號*/private Long id;/*** 省份編號*/private Long provinceId;/*** 城市名稱*/private String cityName;/*** 描述*/private String description;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public Long getProvinceId() {return provinceId;}public void setProvinceId(Long provinceId) {this.provinceId = provinceId;}public String getCityName() {return cityName;}public void setCityName(String cityName) {this.cityName = cityName;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}
}
package org.spring.springboot.dao;import org.apache.ibatis.annotations.Param;
import org.spring.springboot.domain.City;/*** 城市 DAO 接口類**/
public interface CityDao {/*** 根據城市名稱,查詢城市信息** @param cityName 城市名*/City findByName(@Param("cityName") String cityName);
}
package org.spring.springboot.service;import org.spring.springboot.domain.City;/*** 城市業務邏輯接口類**/
public interface CityService {/*** 根據城市名稱,查詢城市信息* @param cityName*/City findCityByName(String cityName);
}
package org.spring.springboot.service.impl;import org.spring.springboot.dao.CityDao;
import org.spring.springboot.domain.City;
import org.spring.springboot.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** 城市業務邏輯實現類**/
@Service
public class CityServiceImpl implements CityService {@Autowiredprivate CityDao cityDao;public City findCityByName(String cityName) {return cityDao.findByName(cityName);}}
package org.spring.springboot.controller;import org.spring.springboot.domain.City;
import org.spring.springboot.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class CityRestController {@Autowiredprivate CityService cityService;@RequestMapping(path="/api/city",method=RequestMethod.GET)public City findCityByName(@RequestParam(value="cityName",required=true) String cityName){return cityService.findCityByName(cityName);}@RequestMapping(path="/test/hotswapp")public String testHotSwapping(){return "測試熱交換";}}
  • 啟動類
package org.spring.springboot;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("org.spring.springboot.dao")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
  • db
/*
Navicat MySQL Data TransferSource Server         : 本地實例
Source Server Version : 50528
Source Host           : localhost:3306
Source Database       : springbootdbTarget Server Type    : MYSQL
Target Server Version : 50528
File Encoding         : 65001Date: 2020-08-08 10:51:48
*/SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
-- Table structure for city
-- ----------------------------
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '城市編號',`province_id` int(10) unsigned NOT NULL COMMENT '省份編號',`city_name` varchar(25) DEFAULT NULL COMMENT '城市名稱',`description` varchar(25) DEFAULT NULL COMMENT '描述',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of city
-- ----------------------------
INSERT INTO `city` VALUES ('1', '1', '郭如飛的家', '郭如飛的家在武漢。');

?

問題總結

  • application.properties屬性文件中文亂碼問題,點擊這里,親測可用。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/530350.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/530350.shtml
英文地址,請注明出處:http://en.pswp.cn/news/530350.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

mysql怎么把datetime類型轉換_mysql怎樣實現time轉datetime

mysql實現time轉datetime的方法&#xff1a;使用在sql語句中【FROM_UNIXTIME(時間值)】&#xff0c;代碼為【insert into test(time) values(FROM_UNIXTIME(%d))",time(NULL)】。mysql實現time轉datetime的方法&#xff1a;FROM_UNIXTIME(time(NULL))將liunx系統的time_t類…

SpringBoot入門二

參考Spring Boot Starters - 御坂研究所 創建自己的starter starter是依賴的一種synthesize&#xff08;合成&#xff09;。 starter會把需要用到的依賴全部包含進來&#xff0c;避免開發者自己手動引入依賴。 starter的邏輯 pom.xml<parent><groupId>org.spri…

Tomcat入門

一&#xff0c;tomcat啟動 雙擊startup.bat,如果出現一閃而過的情況&#xff0c;在文件的末尾添加pause&#xff0c;就可以看到環境變量設置的路徑是否正確 如果無法在電腦的高級系統設置中設置環境變量&#xff0c;可以在setclasspath.bat中設置環境變量 set JAVA_HOMEC:\P…

php mysql 圖像_將圖像插入MySQL并使用PHP檢索圖像

此文可能比較繁瑣&#xff0c;有更好的方法&#xff0c;但是出于教程目的&#xff0c;這是我的"“最佳實踐”的路線。今天&#xff0c;我們將討論一個似乎每個人都有些困惑的話題……在MySQL中存儲BLOB圖像&#xff0c;然后使用PHP再次顯示它們。盡管始終建議不要這樣做&a…

利用Maven逆向工程生成mybatis映射文件

一&#xff0c;pom.xml 注意修改逆向工程配置文件的路徑 <build><pluginManagement><plugins><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1…

mysql update多個表_mysql update 多表 (復制)

定我們有兩張表&#xff0c;一張表為Product表存放產品信息&#xff0c;其中有產品價格列Price&#xff1b;另外一張表是ProductPrice表&#xff0c;我們要將ProductPrice表中的價格字段Price更新為Price表中價格字段的80%。在Mysql中我們有幾種手段可以做到這一點&#xff0c;…

ORA-00907:missing right parenthesis缺少右括號

一&#xff0c;有嵌套查詢&#xff0c;并且子查詢中用了union all合并兩個查詢時&#xff0c;前一個查詢用了order by&#xff0c;那么會報錯并提示ORA-00907:missing right parenthesis缺少右括號&#xff1a; select * from ( select t.* from emp t where t.jobMANAGER ord…

mysql重復記錄大于十的數據庫_面試官:在使用mysql數據庫時,遇到重復數據怎么處理?...

前言前段時間&#xff0c;很多人問我能不能寫一些數據庫的文章&#xff0c;正好自己在測試mysql數據庫性能的時候&#xff0c;出現了一個問題&#xff0c;也就是出現了很多重復的數據&#xff0c;想起來自己long long ago寫過一篇類似的&#xff0c;僅此就拿來總結了一下。如果…

線程組的概念

一&#xff0c;線程組和線程的結構&#xff1a;樹形結構 每個Thread必然存在于一個ThreadGroup中&#xff0c;Thread不能獨立于ThreadGroup存在。 執行main()方法線程的名字是main 如果在new Thread時沒有顯式指定&#xff0c;那么默認將父線程&#xff08;當前執行new Threa…

mysql中ak替換鍵_數據庫:唯一性約束_alternate key(替換鍵) mySQL Oracle 數據庫 ak 唯一性約束...

數據庫:唯一性約束_alternate key(替換鍵) mySQL Oracle 數據庫 ak 唯一性約束數據庫:唯一性約束所謂唯一性約束(unique constraint)不過是數據表內替代鍵的另一個名稱而已。替代鍵(alternate key)可以是數據表內不作為主鍵的其他任何列&#xff0c;只要該鍵對該數據表唯一即可…

Oracle自定義類型

Oracle自定義類型可以通過type/create type來聲明或者創建 一&#xff0c;四種創建方式 1.1&#xff0c;使用create type創建object類型 create or replace type obj_type as object(id number,name varchar2(50 byte),birthday date); 1.2&#xff0c;使用create type創建…

Oracle/mysql查詢語句的執行過程

執行順序 from on join/pivot/unpivot(mysql沒有pivot和unpivot) where group by having select distinct order by limit&#xff08;oralce沒有&#xff09; 書寫順序 select distinct <select_list> from <left_table> <join_type>join <righ…

mysql定時sql腳本_定時執行的SQL腳本

因為要同步一個表&#xff0c;所以每天要同步一次數據&#xff0c;但是對SQL不是精通的我&#xff0c;為了測試寫了一段代碼來測試定時功能創建一個存儲過程&#xff0c;是用來插數據的&#xff0c;沒有輸出和輸出參數create or replace procedure temp_pro asbegininsert into…

mysql xml語句_Mysql語句

xml文件轉義字符處理(1)(2)直接寫轉義后的字符1、mysql里批量修改表內某個字段內的部分數據UPDATE inventory_stockSET batchno REPLACE(batchno,-20-201901,-50-2019)2、ON DUPLICATE KEY UPDATE根據主鍵判斷是新增還是修改(也可以有兩個或多個主鍵)INSERT INTO TABLE (a,c) …

destoon網站mysql分表_destoon : 常用數據庫操作

destoon在初始化系統后系統會自動連接數據庫&#xff0c;并將數據庫操作對象保存在$db。對于數據庫操作方法參考include/db_mysql.class.php函數原型&#xff0c;我來寫幾個常用數據庫操作。1、讀取單條信息$S $db->get_one("SELECT * FROM {$DT_PRE}table WHERE xxxy…

delphi7 mysql控件_Delphi7連接MySql數據庫-DBGrid控件顯示數據

一個簡單的Delphi7小程序&#xff0c;使用MySql數據庫做簡單查詢&#xff0c;用DBGrid控件顯示結果&#xff0c;實現過程如下&#xff1a;(1)在MySql中新建demouser表&#xff0c;插入記錄用于測試。(2)在Delphi7中新建項目。(3)在From中添加組件。組件Panel&#xff1a;pnl1組…

for循環false 終止 python_python3.5.1給用戶3次無效的嘗試,然后終止pgm(Simple FOR循環)...

我需要幫助(新生-2周)。我想得到這段代碼可能的最微小的變化&#xff0c;允許用戶3次在程序中輸入錯誤的值。輸入錯誤值3次后&#xff0c;程序應終止。唯一的要求是代碼必須包含FOR循環。我不知道它是需要一個FOR循環還是3個FOR循環(每次轉換一個)。我嘗試了很多種方案&#xf…

mysql何時會走索引

訪問類型&#xff0c;這里只列出最常見的6種類型 all,index,range,ref,eq_ref&#xff0c;const mysql中explain的type的解釋_dennis211的博客-CSDN博客_explain type 使用不同的運算符時訪問類型不一樣&#xff1a; !、not in、<>、>、<、in(多個值)、or、bet…

mysql數據庫唯一性_在MySQL數據庫中添加唯一性約束,范圍可能嗎?

我有一個使用MySQL的Rails應用程序。我在兩個模型之間有一個has_many :through關聯&#xff0c;如下所述&#xff1a;class Category < ActiveRecord::Basehas_many :category_pairingshas_many :dishes, through: :category_pairings, :inverse_of > :categoriesendclas…

filtic函數 matlab_matlab filtic 函數應用 filter 解差分方程 dft 函數

matlab filtic 函數應用 filter 解差分方程 dft 函數一、 解差分方程說明都在代碼注釋里面了%這里要利用filtic函數 為濾波器的直接II型實現選擇初始條件%求解查分方程 y(n) - 0.4y(n-1) - 0.45y(n-2) 0.45x(n) 0.4x(n-1) - x(n-2)%y(-1) 0 y(-2) 1 x(-1) 1 x(-2) 2%x(n)…