淘宝客网站开发视频教程,商业空间设计说明,电脑系统做的好的网站好,如何查询网站后台地址SpringBoot能够很简单的创建一个直接运行的单体Spring应用
特性#xff1a;
单体Spring应用内置的tomcat、Jetty提供默认的starter来构建配置自动配置Spring和第三方库
推荐一个很好的学习教程#xff0c;https://blog.csdn.net/u010486495/article/details/79348302
1 构…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 parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.0.4.RELEASE/versionrelativePath / !-- lookup parent from repository --/parentdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-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.activeprod那么会加载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 MapLong,User userMap Collections.synchronizedMap(new HashMapLong,User());RequestMapping(path/,methodRequestMethod.GET)public ListUser getUserList(){ListUser userList new ArrayListUser(userMap.values());return userList;}RequestMapping(path/,methodRequestMethod.POST)public String addUser(ModelAttribute User user){userMap.put(user.getId(), user);return success;}RequestMapping(path/{id},methodRequestMethod.GET)public User getUser(PathVariable Long id){return userMap.get(id);}RequestMapping(path/{id},methodRequestMethod.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},methodRequestMethod.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 xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdspringboot/groupIdartifactIdspringboot-mybatis/artifactIdversion0.0.1-SNAPSHOT/versiondescriptionspringboot-mybatis整合/description!-- Spring Boot 启动父依赖 --parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion1.5.1.RELEASE/version/parentdependencies!-- Spring Boot Web 依赖 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- Spring Boot Test 依赖 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency!-- 热交换 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-devtools/artifactIdoptionaltrue/optional/dependency!-- Spring Boot Mybatis 依赖 --dependencygroupIdorg.mybatis.spring.boot/groupIdartifactIdmybatis-spring-boot-starter/artifactIdversion1.2.0/version/dependency!-- MySQL 连接驱动依赖 --dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactId/dependency/dependencies
/project
application.properties
## 数据源配置
spring.datasource.urljdbc:mysql://localhost:3306/springbootdb?useUnicodetruecharacterEncodingutf8
spring.datasource.usernameroot
spring.datasource.passworda123
spring.datasource.driver-class-namecom.mysql.jdbc.Driver## Mybatis 配置
mybatis.typeAliasesPackageorg.spring.springboot.domain
mybatis.mapperLocationsclasspath:mapper/*.xml CityMapper.xml
mybatis映射文件在src\main\resources\mapper目录创建一个CityMapper.xml文件
使用逆向工程生成代码
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespaceorg.spring.springboot.dao.CityDaoresultMap idBaseResultMap typeorg.spring.springboot.domain.Cityresult columnid propertyid /result columnprovince_id propertyprovinceId /result columncity_name propertycityName /result columndescription propertydescription //resultMapparameterMap idCity typeorg.spring.springboot.domain.City/sql idBase_Column_Listid, province_id, city_name, description/sqlselect idfindByName resultMapBaseResultMap parameterTypejava.lang.Stringselectinclude refidBase_Column_List /from citywhere city_name like %${cityName}%/select/mapperentity、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,methodRequestMethod.GET)public City findCityByName(RequestParam(valuecityName,requiredtrue) 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_CHECKS0;-- ----------------------------
-- 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)
) ENGINEInnoDB AUTO_INCREMENT2 DEFAULT CHARSETutf8;-- ----------------------------
-- Records of city
-- ----------------------------
INSERT INTO city VALUES (1, 1, 郭如飞的家, 郭如飞的家在武汉。);问题总结 application.properties属性文件中文乱码问题点击这里亲测可用。