springboot开发

热部署

手工启动热部署

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

激活热部署:Ctrl + F9

自动启动热部署

1.settings->Compiler->Build project automatically
2.ctrl+shift+alt+/   ---->>>  compiler.automake.allow.when.app.running  √
激活方式:Idea失去焦点5秒后启动热部署

热部署范围配置

默认不触发重启的目录列表:
/META-INF/maven
/META-INF/resources
/resources
/static
/public
/templates

自定义不参与重启排除项

devtools:
  restart:   
    exclude: public/**,static/**

关闭热部署

设置高优先级属性禁用热部署

public static void main(String[] args) {   
    System.setProperty("spring.devtools.restart.enabled", "false");   
    SpringApplication.run(SSMPApplication.class);
}

配置高级

@ConfigurationProperties

使用@ConfigurationProperties为第三方bean绑定属性

@Bean
@ConfigurationProperties(prefix = "datasource")
public DruidDataSource dataSource(){    
    DruidDataSource ds = new DruidDataSource();    
    return ds;
}
servers:
 
  ip-address: 192.168.0.2   
  port: 2345
  timeout: -1
  
datasource:  
  driverClassName: com.mysql.jdbc.Driver

@EnableConfigurationProperties注解可以将使用@ConfigurationProperties注解对应的类加入Spring容器

@SpringBootApplication
@EnableConfigurationProperties(ServerConfig.class)
public class DemoApplication {
    
}
//@Component
@Data
@ConfigurationProperties(prefix = "servers")
public class ServerConfig {
    private String ipAddress;
    private int port;
    private long timeout;
}

@EnableConfigurationProperties与@Component不能同时使用

解除使用@ConfigurationProperties注释警告
在这里插入图片描述

<dependency>   
    <groupId>org.springframework.boot</groupId>   
    <artifactId>spring-boot-configuration-processor</artifactId>
</dependency>

宽松绑定/松散绑定

@ConfigurationProperties绑定属性支持属性名宽松绑定
@Value引用单个属性的方式不支持宽松绑定

servers:
  #  ipAddress: 192.168.0.2       # 驼峰模式
  #  ipaddress: 192.168.0.2
  #  ip_address: 192.168.0.2      # unline  下划线模式
  ip-address: 192.168.0.2       # 烤肉串模式  0-0-0-0---------
  #  IPADDRESS: 192.168.0.2
  #  IP_ADDRESS: 192.168.0.2      # 常量模式
  #  IP_ADD_R-E_SS: 192.168.0.2
  port: 2345
  timeout: -1

绑定前缀名命名规范:仅能使用纯小写字母、数字、下划线作为合法的字符

@Bean
@ConfigurationProperties(prefix = "datasource")//datasource必须是小写
public DruidDataSource dataSource(){
    DruidDataSource ds = new DruidDataSource();
    return ds;
}

常用计量单位绑定

计量单位

@Component
@Data
@ConfigurationProperties(prefix = "servers")
public class ServerConfig {
    private String ipAddress;
    private int port;
    private long timeout;

    @DurationUnit(ChronoUnit.HOURS)//服务器超时时间单位,以小时为单位
    private Duration serverTimeOut;

    @DataSizeUnit(DataUnit.MEGABYTES)//数据大小单位,以MB为单位
    private DataSize dataSize;
}
servers:
  ip-address: 192.168.0.2       # 烤肉串模式  0-0-0-0---------
  port: 2345
  timeout: -1
  
  serverTimeOut: 3
  dataSize: 10

数据校验

开启数据校验有助于系统安全性。
1.增加坐标

<!--数据校验-->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>
<!--使用hibernate框架提供的校验器实现类-->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>
@Component
@Data
@ConfigurationProperties(prefix = "servers")
//2.开启对当前bean的属性注入校验
@Validated
public class ServerConfig {
    private String ipAddress;

    //3.设置具体的规则
    @Max(value = 8888,message = "最大值不能超过8888")
    //@Min(value = 202, message = "最小值不低于202")
    private int port;
    private long timeout;
    
}

测试

加载测试专用属性

在启动测试环境时可以通过properties参数设置测试环境专用的属性。

//properties属性可以为当前测试用例添加临时的属性配置
//@SpringBootTest(properties = {"test.prop=testValue1"})

//args属性可以为当前测试用例添加临时的命令行参数
//@SpringBootTest(args={"--test.prop=testValue2"})
@SpringBootTest(properties = {"test.prop=testValue1"}, args = {"--test.prop=testValue2"})
public class PropertiesAndArgsTest {

    @Value("${test.prop}")
    private String msg;

    @Test
    void testProperties() {
        System.out.println(msg);
    }

}

优势:比多环境开发中的测试环境影响范围更小,仅对当前测试类有效。

加载测试专用配置

使用@Import注解加载当前测试类专用的配置。
MsgConfig.java

@Configuration
public class MsgConfig {

    @Bean
    public String msg() {
        return "bean msg";
    }

}
测试类
@SpringBootTest
@Import({MsgConfig.class})
public class ConfigurationTest {

    @Autowired
    private String msg;

    @Test
    void testConfiguration() {
        System.out.println(msg);
    }

}

Web环境模拟测试

模拟端口

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)//随机端口
public class WebTest {    

    @Test    
    void testRandomPort () {    
    }
}      

虚拟请求测试

//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {

    @Test
    void testWeb(@Autowired MockMvc mvc) throws Exception {
        //  http://localhost:8080/books
        //创建虚拟请求,当前访问/books
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        //执行对应的请求
        mvc.perform(builder);
    }

虚拟请求状态匹配

@Test
void testStatus(@Autowired MockMvc mvc) throws Exception {
    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
    ResultActions action = mvc.perform(builder);

    //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
    //定义本次调用的预期值
    StatusResultMatchers status = MockMvcResultMatchers.status();
    //预计本次调用时成功的:状态200
    ResultMatcher ok = status.isOk();
    //添加预计值到本次调用过程中进行匹配
    action.andExpect(ok);

}

虚拟请求响应体匹配

@Test
void testBody(@Autowired MockMvc mvc) throws Exception {
    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
    ResultActions action = mvc.perform(builder);

    //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
    //定义本次调用的预期值
    ContentResultMatchers content = MockMvcResultMatchers.content();
    ResultMatcher result = content.string("springboot2");
    //添加预计值到本次调用过程中进行匹配
    action.andExpect(result);

}

虚拟请求响应体(json)匹配

@Test
void testJson(@Autowired MockMvc mvc) throws Exception {
    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
    ResultActions action = mvc.perform(builder);

    //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
    //定义本次调用的预期值
    ContentResultMatchers content = MockMvcResultMatchers.content();
    ResultMatcher result = content.json("{\"id\":1,\"name\":\"springboot2\",\"type\":\"springboot\",\"description\":\"springboot\"}");
    //添加预计值到本次调用过程中进行匹配
    action.andExpect(result);

}

虚拟请求响应头匹配

@Test
void testContentType(@Autowired MockMvc mvc) throws Exception {
    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
    ResultActions action = mvc.perform(builder);

    //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
    //定义本次调用的预期值
    HeaderResultMatchers header = MockMvcResultMatchers.header();
    ResultMatcher contentType = header.string("Content-Type", "application/json");
    //添加预计值到本次调用过程中进行匹配
    action.andExpect(contentType);

}

数据层测试回滚

为测试用例添加事务,SpringBoot会对测试用例对应的事务提交操作进行回滚。

@Transactional和@SpringBootTest搭配着使用,首先它是个测试类,然后执行的操作不想提交,就使用@Transactional进行回滚,数据库中没有添加多出来数据。

@Rollback,如果想在测试用例中提交事务,可以通过@Rollback注解设置,@Rollback(true)就是回滚,不提交事务;@Rollback(false)是不回滚,测试类提交事务。

@SpringBootTest
@Transactional
@Rollback(true)
public class DaoTest {

    @Autowired
    private BookService bookService;

    @Test
    void testSave() {
        Book book = new Book();
        book.setName("springboot3");
        book.setType("springboot3");
        book.setDescription("springboot3");

        bookService.save(book);
    }

}

测试用例数据设定

测试用例数据通常采用随机值进行测试,使用SpringBoot提供的随机数为其赋值。

testcase:
  book:
    id: ${random.int}
    id2: ${random.int(10)}
    type: ${random.int!5,10!}
    name: \u9ED1\u9A6C${random.value}
    uuid: ${random.uuid}
    publishTime: ${random.long}
    
    ${random.int}表示随机整数
    ${random.int(10)}表示10以内的随机数
    ${random.int(10,20)}表示1020的随机数
其中()可以是任意字符,例如[]!!均可
@Component
@Data
@ConfigurationProperties(prefix = "testcase.book")
public class BookCase {
    private int id;
    private int id2;
    private int type;
    private String name;
    private String uuid;
    private long publishTime;
}
  • 18
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值