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.mzph.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)…