springboot:hello world

项目地址:https://github.com/snjl/springboot_helloworld.git

Spring Boot的主要优点:

  • 为所有Spring开发者更快的入门

  • 开箱即用,提供各种默认配置来简化项目配置

  • 内嵌式容器简化Web项目

  • 没有冗余代码生成和XML配置的要求

快速入门

主要目标是完成Spring Boot基础项目的构建,并且实现一个简单的Http请求处理,通过这个例子对Spring Boot有一个初步的了解,并体验其结构简单、开发快速的特性。

使用Maven构建项目

  1. 通过SPRING INITIALIZR工具产生基础项目
  • 访问:http://start.spring.io/
  • 选择构建工具Maven Project、Spring
  • Boot版本1.3.2以及一些工程基本信息,可参考下图所示
    image
    点击Generate Project下载项目压缩包
  1. 解压项目包,并用IDE以Maven项目导入
  • 菜单中选择File–>New–>Project from Existing Sources
  • 选择解压后的项目文件夹,点击OK
  • 点击Import project from external model并选择Maven,点击Next到底为止。
  • 选择Java SDK的时候请选择Java 7以上的版本

项目结构

image

通过上面步骤完成了基础项目的创建,如上图所示,Spring Boot的基础结构共三个文件(具体路径根据用户生成项目时填写的Group所有差异):

  • src/main/java下的程序入口:Chapter1Application
  • src/main/resources下的配置文件:application.properties
  • src/test/下的测试入口:Chapter1ApplicationTests

生成的Chapter1Application和Chapter1ApplicationTests类都可以直接运行来启动当前创建的项目,由于目前该项目未配合任何数据访问或Web模块,程序会在加载完Spring之后结束运行。

其中,@SpringBootApplication的这个注解是声明当前类为sprinboot的入口类。而一个springboot项目内有且只能有一个这个注解存在。

引入Web模块

引入Web模块,需在pom.xml中添加spring-boot-starter-web模块:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

编写HelloWorld服务

  • 创建package命名为com.example.demo.web(根据实际情况修改)
  • 创建HelloController类,内容如下
1
2
3
4
5
6
7
8
9
10
11
12
package com.exmaple.demo.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";
}
}

启动主程序(可以在命令行中使用mvn spring-boot:run,或者通过idea启动),打开浏览器访问http://localhost:8080/hello,可以看到页面输出Hello World
image

编写单元测试用例

打开的src/test/下的测试入口Chapter1ApplicationTests类。下面编写一个简单的单元测试来模拟http请求,具体如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.exmaple.demo;

import com.exmaple.demo.web.HelloController;
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 static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.Matchers.equalTo;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MockServletContext.class)
@WebAppConfiguration
public class Chapter1ApplicationTests {

private MockMvc mvc;

@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}

@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World")));
}

}

使用MockServletContext来构建一个空的WebApplicationContext,这样我们创建的HelloController就可以在@Before函数中创建并传递到MockMvcBuilders.standaloneSetup()函数中。

其中的SpringBootTest注解,原来为SpringApplicationConfiguration,现在已弃用。如果在判断equalTo时判断不一致,会报错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
java.lang.AssertionError: Response content
Expected: "Hello World1"
but: was "Hello World"
Expected :Hello World1
Actual :Hello World
<Click to see difference>


at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$string$3(ContentResultMatchers.java:130)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at com.exmaple.demo.Chapter1ApplicationTests.getHello(Chapter1ApplicationTests.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

打包

在 POM 文件添加插件:

1
2
3
4
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

当运行“mvn package”进行打包时,会打包成一个可以直接运行的 JAR 文件,使用“java -jar”命令就可以直接运行。

开箱即用模块

Spring Boot提供了很多”开箱即用“的依赖模块,都是以spring-boot-starter-xx作为命名的。下面列举一些常用的模块。

  • spring-boot-starter-logging :使用 Spring Boot 默认的日志框架 Logback。
  • spring-boot-starter-log4j :添加 Log4j 的支持。
  • spring-boot-starter-web :支持 Web 应用开发,包含 Tomcat 和 spring-mvc。
  • spring-boot-starter-tomcat :使用 Spring Boot 默认的 Tomcat 作为应用服务器。
  • spring-boot-starter-jetty :使用 Jetty 而不是默认的 Tomcat 作为应用服务器。
  • spring-boot-starter-test :包含常用的测试所需的依赖,如 JUnit、Hamcrest、Mockito 和 spring-test 等。
  • spring-boot-starter-aop :包含 spring-aop 和 AspectJ 来支持面向切面编程(AOP)。
  • spring-boot-starter-security :包含 spring-security。
  • spring-boot-starter-jdbc :支持使用 JDBC 访问数据库。
  • spring-boot-starter-redis :支持使用 Redis。
  • spring-boot-starter-data-mongodb :包含 spring-data-mongodb 来支持 MongoDB。
  • spring-boot-starter-data-jpa :包含 spring-data-jpa、spring-orm 和 Hibernate 来支持 JPA。
  • spring-boot-starter-amqp :通过 spring-rabbit 支持 AMQP。
  • spring-boot-starter-actuator : 添加适用于生产环境的功能,如性能指标和监测等功能。

Java Config 自动配置

Spring Boot 推荐采用基于 Java Config 的配置方式,而不是传统的 XML。例如,@Configuration、@Bean、@EnableAutoConfiguration、@CompomentScan、@PropertySource、@Repository、@Service、@RestController等。

-------------本文结束 感谢您的阅读-------------