每次修改java后,都需要重新運行main方法才能生效。這樣會降低開發效率。我們可以使用
spring boot提供的開發工具來實現熱部署,為項目加上一下依賴:
<!-- 開發環境增加熱部署依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
等待maven構建后,發現project項目名字后面會增加 devtools

運行單元測試。
單元測試對於程序來說非常重要,不僅能增強程序的健壯性,而且也為程序的重構提供了依據,目前很多開源項目的測試覆蓋率高達90%;
spring boot運行web應用,只需要執行main方法即可,那么如何測試web程序呢?
那就需要使用spring boot的單元測試。
1.spring boot提供了@springbootTest注解,可以讓我們在單元測試中測試spring boot的程序。
需要加入依賴,使用maven構建
<!-- 增加spring-boot-starter-test依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies>
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class RandomPortTest { @Autowired private TestRestTemplate restTemplate;
@Test public void testHello() { //測試hello 方法 String result = restTemplate.getForObject("/hello", String.class); assertEquals("Hello World!", result); }
在測試類中加入了@RunWith,@SpringBootTest注解,
其中為spring boot test配置了webEnvironment屬性,表示在運行測試時,會為web容器隨機分配端口。
在測試方法中,使用@Test注解修飾。使用TestResultTemplate調用“/hello”服務。
這種測試會啟動web容器。

只測試業務組件,不測試web容器,那么只啟動spring的容器。
MyService.java @Service public class MyService { public String helloService() { return "hello"; } }
MyServiceTest.java @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE) public class MyServiceTest { @Autowired private MyService myService; @Test public void testHello() { String result = myService.helloService(); System.out.println(result); } }
新建了一個MyService服務類,MyServiceTest會對該類進行測試,直接在測試類中注入MyService實例
SpringBootTest的webEnvironment屬性會被設置為NONE,因此web容器不會被啟動。
