通过 IDEA 创建 SpringBoot 工程
本次选择的 SpringBoot 版本是1.5.9.RELEASE
打开 IDEA ,点击 File -> New -> Project -> Spring Initializr
选择Project SDK: JDK 1.8
选择Initializr Service URL: Default
点击 Next,等待一会,有时会提示 Initialization failed,重新尝试即可
修改Group、Artifact 即可,可以适当调整一下Package
添加起步依赖:Web starter 依赖
配置工程名称及工程存放路径
生成的项目目录结构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<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
默认的pom.xml 文件内主要内容:
parent 标签表示从 spring-boot-starter-parent 继承的版本号
properties 标签内定义编码格式,jdk 版本
dependencies 标签表示使用哪些起步依赖
build 标签表示使用哪些插件
SpringBoot Application 类
1 | package com.example.springboot.hello; |
@SpringBootApplication 注解是一个组合注解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
44
45
46
47
48
49
50
51
52
53
54
55package org.springframework.boot.autoconfigure;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
@AliasFor(
annotation = EnableAutoConfiguration.class,
attribute = "exclude"
)
Class<?>[] exclude() default {};
@AliasFor(
annotation = EnableAutoConfiguration.class,
attribute = "excludeName"
)
String[] excludeName() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackages"
)
String[] scanBasePackages() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackageClasses"
)
Class<?>[] scanBasePackageClasses() default {};
}
其包含如下三个注解:
@Configuration : 表示该类使用Spring基于Java配置
@ComponentScan : 启用组件扫描
@EnableAutoConfiguration : Spring Boot 魔力来源,启用自动配置
创建一个 Controller
src/main/java/com/example/springboot/hello/controller/HellController.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package com.example.springboot.hello.controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "Greetings from Spring Boot!";
}
}
@RestController 注解表示该Controller是RESTful风格接口
@RequestMapping 注解定义请求URL和请求方法
运行 SpringBoot Application
有很多种方式可以运行 SpringBoot Application。
开发过程中可以直接执行 Application main 方法,或者 通过maven install 方式启动
打包可以通过maven package 打包
打包后运行可以通过java -jar XXX.jar 方式运行可执行 jar 包
一般控制台可以看到如下输出: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 . ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.9.RELEASE)
2017-11-29 14:46:28.397 INFO 9916 --- [ main] c.e.s.hello.SpringBootHelloApplication : Starting SpringBootHelloApplication on DESKTOP-1MESJ85 with PID 9916 (started by Richard in D:\lxmuse-spring-boot\building an application with spring boot\spring-boot-hello)
2017-11-29 14:46:28.400 INFO 9916 --- [ main] c.e.s.hello.SpringBootHelloApplication : No active profile set, falling back to default profiles: default
2017-11-29 14:46:28.492 INFO 9916 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5e955596: startup date [Wed Nov 29 14:46:28 CST 2017]; root of context hierarchy
2017-11-29 14:46:29.600 INFO 9916 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-11-29 14:46:29.608 INFO 9916 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-11-29 14:46:29.609 INFO 9916 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-11-29 14:46:29.672 INFO 9916 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-11-29 14:46:29.673 INFO 9916 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1187 ms
2017-11-29 14:46:29.761 INFO 9916 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-11-29 14:46:29.764 INFO 9916 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-11-29 14:46:29.764 INFO 9916 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-11-29 14:46:29.765 INFO 9916 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-11-29 14:46:29.765 INFO 9916 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-11-29 14:46:29.999 INFO 9916 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5e955596: startup date [Wed Nov 29 14:46:28 CST 2017]; root of context hierarchy
2017-11-29 14:46:30.037 INFO 9916 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/index],methods=[GET]}" onto public java.lang.String com.example.springboot.hello.controller.HelloController.index()
2017-11-29 14:46:30.040 INFO 9916 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-29 14:46:30.041 INFO 9916 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-29 14:46:30.062 INFO 9916 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-29 14:46:30.062 INFO 9916 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-29 14:46:30.085 INFO 9916 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-29 14:46:30.168 INFO 9916 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-11-29 14:46:30.206 INFO 9916 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-11-29 14:46:30.212 INFO 9916 --- [ main] c.e.s.hello.SpringBootHelloApplication : Started SpringBootHelloApplication in 2.122 seconds (JVM running for 3.326)
访问 SpringBoot Application
同理有很多种方式可以访问 SpringBoot Application。
如果是 GET 请求,可以直接通过浏览器访问
如果是 其他 请求,可以使用浏览器REST client 模拟请求,或者使用 PostMan 等软件模拟请求
使用 PostMan 发起 GET 请求,地址是:localhost:8080/index
SpringBoot 工程默认的地址是localhost:8080
可以看到返回结果是 Greetings from Spring Boot!
添加单元测试
1 | package com.example.springboot.hello; |
也可以对 HelloController 做单独的单元测试: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
41package com.example.springboot.hello.controller;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
class) (SpringRunner.
(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerTest {
private int port;
private URL base;
private TestRestTemplate template;
public void setUp() throws Exception {
this.base = new URL("http://localhost:" + port + "/index");
}
public void testIndex() throws Exception {
ResponseEntity<String> response = template.getForEntity(base.toString(),
String.class);
assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}
具体代码已上传GitHub-lxmuse