- 创建项目
- 启动类出错
- 打包速度
- 数据库配置
- 链接失败密码问题
- mybatis-plus
- 表的匹配和id自增
- 拦截器
- 日志记录
- 校验
- 计量单位
- 临时专用属性
- 临时专用配置
- 测试类
- 随机端口
- 发送虚拟请求
- 事务回滚
- 配置文件随机值
- 数据层技术选型
创建项目
首先就是创建,创建SpringBoot工程方法很多。工具自动,人工手动。
工具经典方法:
选择JDK时,建议1.8
之后就是耐心等待,网好一次过,网卡请努力
web工程
mybatis,如使用mybatis-plus手动pom
选择好所需,下一步
创建完成,刷新maven即可使用。
或者使用阿里,速度更快,但配置和项目结构有些不同。
手动方式无非复制之前创建好的项目,修改名称,**注意pom中名称的修改,**然后刷新pom。
启动类出错IDEA没有加载启动类?
打开启动类,等待spring管理
然后运行就好了
打包速度关闭test
目前还是很慢,但有提升。
数据库配置 链接失败密码问题测试多种组合
数字和特殊字符识别错误(进制和格式问题)
例子:
dataSource: password: 9.
测试类
@SpringBootTest
class Springboot13ConfigurationApplicationTests {
@Value("${dataSource.password}")
private String password;
@Test
void contextLoads() {
System.out.println(password);
}
}
使用""包裹密码,解决问题
mybatis-plus 表的匹配和id自增 拦截器配置分页拦截器
@Configuration
public class MPConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
//配置mp拦截器
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//配置具体拦截器
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
日志记录
红框必备
level:后添加mapper包即可
使用mybatis修改第一行,删除-plus
file-name-pattern使用全路径
校验javax.validation validation-api
实体类
//2.开启校验
@Validated
public class ServletConfig {
private String ipAddress;
//3.设置校验规则
@Max(value = 100,message = "最大值不该超过100")
private int port;
private long timeout;
}
org.hibernate.validator hibernate-validator
设置最大值100的限制,实际101
servlet: ipAddress: 192.168.0.1 port: 101 timeout: -1
超过提示
计量单位实体类
@ConfigurationProperties(prefix = "servlet")
@Component
@Data
public class ServletConfig {
private String ipAddress;
private int port;
@DurationUnit(ChronoUnit.HOURS)
private Duration timeout;
}
servlet: ipAddress: 192.168.0.1 port: 50 timeout: 10
启动类
ServletConfig bean = run.getBean(ServletConfig.class); System.out.println(bean);临时专用属性
测试时yml中无配置,如有配置注解优先
方法一:
@SpringBootTest(properties = {"test.prop = testValue1"})
public class PropertiesAndArgsTest {
@Value("${test.prop}")
private String prop;
@Test
void testProperties(){
System.out.println(prop);
}
}
方法二:
@SpringBootTest(args = {"--test.prop=testValue2"})
public class PropertiesAndArgsTest {
@Value("${test.prop}")
private String prop;
@Test
void testProperties(){
System.out.println(prop);
}
}
args优先级大于properties
临时专用配置不使用配置类注解
// @Configuration
public class MsgConfig {
@Bean
public String msg(){
return "textMsgConfig";
}
}
使用Import注解可以加载临时配置
@SpringBootTest
@Import(MsgConfig.class)
public class TestMsgConfig {
@Autowired
private String msg;
@Test
void testMsg(){
System.out.println(msg);
}
}
测试类
随机端口
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestWeb {
@Test
void test(){
}
}
发送虚拟请求
controller
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping
public String getById(){
System.out.println("getById...");
return "books";
}
}
test
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class TestWeb {
@Autowired
private MockMvc mockMvc;
@Test
void test() throws Exception {
//虚拟路径
MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/books");
//执行
mockMvc.perform(mockHttpServletRequestBuilder);
}
}
设置预期值
状态预期
MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/books");
ResultActions perform = mockMvc.perform(mockHttpServletRequestBuilder);
//设置预期值
//定义预期值 status模拟状态
StatusResultMatchers status = MockMvcResultMatchers.status();
//预计状态
ResultMatcher ok = status.isOk();
//实际和预计比对
perform.andExpect(ok);
成功无输出
失败有提示
MockHttpServletRequest:
HTTP Method = GET
Request URI = /books1
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<200> but was:<404>
Expected :200
Actual :404
内容请求体预期
和controller中return比较
@Test
void test2() throws Exception {
MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/books");
ResultActions perform = mockMvc.perform(mockHttpServletRequestBuilder);
//设置预期值
//定义预期值 content
ContentResultMatchers content = MockMvcResultMatchers.content();
//预计内容
ResultMatcher ok = content.string("book");
//实际和预计比对
perform.andExpect(ok);
}
成功无输出
失败有提示
MockHttpServletRequest:
HTTP Method = GET
Request URI = /books
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = com.yuhang.controller.BookController
Method = com.yuhang.controller.BookController#getById()
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"5"]
Content type = text/plain;charset=UTF-8
Body = books
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Response content expected: but was:
Expected :book
Actual :books
JSON预期
实体类
@Data
public class Book {
private Integer id;
private String name;
private Integer money;
}
controller
@RestController
@RequestMapping("/books")
public class BookController {
// @GetMapping
// public String getById(){
// System.out.println("getById...");
// return "books";
// }
@GetMapping
public Book getById(){
System.out.println("getById...");
Book book = new Book();
book.setId(1);
book.setName("xiyou");
book.setMoney(100);
return book;
}
}
test
@Test
void testJson() throws Exception {
MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/books");
ResultActions perform = mockMvc.perform(mockHttpServletRequestBuilder);
//设置预期值
//定义预期值 content
ContentResultMatchers content = MockMvcResultMatchers.content();
//预计json
ResultMatcher ok = content.json("{"id":1,"name":"xiyo","money":10}");
//实际和预计比对
perform.andExpect(ok);
}
成功无输出
失败有提示
MockHttpServletRequest:
HTTP Method = GET
Request URI = /books
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = com.yuhang.controller.BookController
Method = com.yuhang.controller.BookController#getById()
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = {"id":1,"name":"xiyou","money":100}
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: money
Expected: 10
got: 100
; name
Expected: xiyo
got: xiyou
以上可以写一起一起匹配
事务回滚需要提交事务加@Rollback(false)
@SpringBootTest
//事务回滚
@Transactional
//提交事务
@Rollback(false)
public class TestMP {
@Autowired
private BookService bookService;
@Test
void save(){
Book book = new Book();
book.setName("xiyou");
book.setMoney(100);
bookService.save(book);
}
}
配置文件随机值
数据层技术选型
数据源
不配置DataSource默认HikariCP
spring:
h2:
console:
enabled: true
path: /h2
datasource:
url: jdbc:h2:~/test
username: sa
password: 123456
持久化
内置持久化解决方案——JdbcTemplate
org.springframework.boot spring-boot-starter-jdbc
@SpringBootTest
public class TestJdbc {
@Test void testGetAll(@Autowired JdbcTemplate jdbcTemplate){
String sql = "select * from tbl_book";
// List
数据库
com.h2database h2 org.springframework.boot spring-boot-starter-data-jpa
spring:
h2:
console:
enabled: true
path: /h2
datasource:
url: jdbc:h2:~/test
username: sa
password: 123456
网页输入http://localhost:8080/h2登录


![【Springboot】springboot使用记录[个人版] 【Springboot】springboot使用记录[个人版]](http://www.mshxw.com/aiimages/31/862761.png)
