日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot入门一

發布時間:2025/3/8 javascript 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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屬性文件中文亂碼問題,點擊這里,親測可用。

總結

以上是生活随笔為你收集整理的SpringBoot入门一的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 亚洲精品激情 | 欧美精品国产一区 | 成人理论视频 | 日本精品免费视频 | 姐姐你真棒插曲快来救救我电影 | 91吃瓜今日吃瓜入口 | av不卡免费| 久久久久一区二区三区 | 午夜大片在线观看 | 成年人在线观看av | 福利午夜视频 | 一二三精品| 婷婷色综合 | xx视频在线 | 色六月婷婷 | 日本成人在线免费视频 | 极品美女被c | 亚洲少妇毛片 | 91影院在线免费观看 | 九色综合网 | 日本不卡一区二区在线观看 | 国产精品免费视频一区 | 欧洲中文字幕日韩精品成人 | www.99在线 | 对白刺激国产子与伦 | 成人精品一区二区三区在线 | 四虎精品永久在线 | 国产成人免费视频 | h片在线看 | 成人无码www在线看免费 | 色爱av综合| 91免费在线看 | 在线观看福利片 | 农村激情伦hxvideos | 欧美一区二区区 | 深夜福利亚洲 | 少妇高潮一区二区三区 | 草莓视频一区二区三区 | 理论片琪琪午夜电影 | 欧美成人精品一区二区男人小说 | 精品久久一 | 日韩av网站在线观看 | 草逼视频免费看 | 少妇一级1淫片 | 亚洲在线资源 | av色先锋 | av日韩在线播放 | 伊人青青操 | 欲乱美女 | 少妇高潮视频 | 国产网红av | 99精品国产成人一区二区 | 91热爆视频| 国产午夜一区二区三区 | 体内射精一区二区 | 网站一区二区 | 国产嫩草av | 久久成人在线 | 熟女少妇a性色生活片毛片 亚洲伊人成人网 | 亚洲乱色熟女一区二区三区 | 久久久久亚洲色欲AV无码网站 | av免播放器 | 无码播放一区二区三区 | 久久久久成人网 | 成人777| 国产精品一区二区三区四 | 色综合av在线 | 精品精品| 91麻豆视频在线观看 | 国产污污| 欧美色xxxx | 一区三区在线 | 女女百合高h喷汁呻吟玩具 www.亚洲一区 | 精品中文字幕一区 | 182tv午夜福利在线观看 | 久久国产精品无码网站 | 一级片视频免费观看 | 亚洲天堂2013 | 狠狠草视频 | 边啃奶头边躁狠狠躁 | 麻豆精品国产 | a级国产毛片 | 午夜天堂视频 | 97超碰人人澡 | 午夜精品久久久久久久99热黄桃 | 会喷水的亲姐姐 | 欧美性猛交ⅹ乱大交3 | 可以在线观看av的网站 | 欧洲mv日韩mv国产 | 让男按摩师摸好爽 | 国产高清精品一区 | 无码少妇精品一区二区免费动态 | 欧美色999 | 欧洲视频一区二区三区 | 午夜电影福利网 | 午夜国产在线观看 | 国产美女久久久 | 97超碰成人 | 日本精品人妻无码免费大全 |