打开“IDEA”-“new Project”-“Spring Initializr”-填写“group”和"artifact"-勾选“web”(开启web功能)-单击“下一步”。IDEA会自动下载Spring Boot工程的模板。
4.2.1 项目结构
创建完工程后,工程的目录结构如下:
-src
-main
-java
-package
-SpringbootApplication
-resouces
-statics
-templates
-application.yml
-test
-pom
各目录含义如下。
- pom文件为依赖管理文件。
- resouces为资源文件夹。
- statics为静态资源。
- templates为模板资源。
- application.yml为配置文件。
- SpringbootApplication为程序的启动类。
4.2.2 在Spring Boot工程中构建Web
打开用IDEA创建的项目,其依赖管理文件pom.xml有spring-boot-starter-web和spring-boot-starter-test的起步依赖。其中,spring-boot-starter-web为Web功能的起步依赖,它会自动导入与Web相关的依赖。spring-boot-starter-test为Spring Boot测试功能的起步依赖,它会导入与Spring Boot测试相关的依赖。代码如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
在工程的代码包的主目录下有一个SpringbootFirstApplication的类,该类是程序的启动类,代码如下
@SpringBootApplication
public class SpringbootfirstApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootfirstApplication.class, args);`在这里插入代码片`
}
}
其中,@SpringBootApplication注解包含了@SpringBootConfiguration、@EnableAuto-Configuration和@ComponentScan,开启了包扫描、配置和自动配置功能。
这是一个完整的、具有Web功能的工程,为了演示Web效果,建一个Web层的Controller,代码如下:
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index(){
return "Greetings from Spring Boot!";
}
}
其中,@RestController注解表明这个类是一个RestController。@RestController是Spring 4.0版本的一个注解,它的功能相当于@Controller注解和ResponseBody注解这和。@RequestMapping注解是配置请求地址的Url映射的。
启动SpringbootfirstApplication的main 方法,Spring Boot程序启动。在控制台会打印启动的日志,程序的默认端口为8080。
打开浏览器,在浏览器上输入“http://localhost:8080/hello”, 浏览器会显示“Greetings from Spirng Boot!"
你公不会觉得Spring Boot的确很神奇?Spring Boot的神奇之处在于,在程序中没有做web.xml的配置,也没有做SpringMVC的配置,甚至都不用部署在Tomcat上,就可以构建一个具备Web功能的工程。其实,Spring Boot自动为你做了这些配置,并且它默认内嵌了Tomcat容器。
4.2.3 Spring Boot的测试
Spring Boot开启测试也非常简单,只需要加@RunWith(SpringRunner.class)和@SpringBootTest注解,在@SpringBootTest注解加上Web测试环境的端口为随机端口的配置。TestRestTemplate类为RestTemplate测试类,RestTemplate用于远程调用Http API接口。测试代码如下:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerTest {
@LocalServerPort
private int port;
private URL base;
@Autowired
private TestRestTemplate template;
@Before
public void setUp() throws Exception{
this.base = new URL("http://localhost:"+port+"/hello");
}
@Test
public void getHello() throws Exception{
ResponseEntity<String> response = template.getForEntity(base.toString(),String.class);
assertEquals(response.getBody(),"Greetings from Spring Boot!");
}
}
启动测试类的getHello()方法,通过控制台可以发现Spring Boot程序会先启动,然后运行测试代码,最后测试通过。