一、介绍
随着动态语言的流行(Ruby、 Groovy、 scala、 Node.js), Java的开发显得格外的笨重:繁多的配置、 低下的开发效率、 复杂的部署流程以及第三方技术集成难度大 。
在上述环境下, Spring Boot应运而生。它使用“习惯优于配置”(项目中存在大量的配理, 此外还内置一个习惯性的配置, 让你无须手动进行配置) 的理念让你的项目快速运行起来 。 使用 Spring Boot很容易创建一个独立运行(运行 jar,内嵌 Servlet容器)、准生产级别的基子 Spring 框架的项目, 使用 Spring Boot你可以不用或者只需要很少的 Spring配置。
优点:
- 快速构建项目;
- 对主流开发框架的无配置集成;
- 项目可独立运行,无须外部依赖Servlt容器;
- 提供运行时的应用监控;
- 极大地提高了开发、部署效率;
- 与云计算的天然集成。
二、入门程序
1、项目搭建
第一步:新建一个spring boot的maven项目,设置spring boot的parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
说明:Spring boot的项目必须要将parent设置为spring boot的parent,该parent包含了大量默认的配置,大大简化了我们的开发。
第二步:导入spring boot的web支持
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
第三步:添加Spring boot的插件
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
第四步:编写第一个Spring Boot的应用
@Controller
@SpringBootApplication
@Configuration
public class HelloApplication {
@RequestMapping("hello")
@ResponseBody
public String hello(){
return "hello world!";
}
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
代码说明:
1、@SpringBootApplication:Spring Boot项目的核心注解,主要目的是开启自动配置。;
2、@Configuration:这是一个配置Spring的配置类;
3、@Controller:标明这是一个SpringMVC的Controller控制器;
4、main方法:在main方法中启动一个应用,即:这个应用的入口;
2、项目运行
第五步:启动应用
在Spring Boot项目中,启动的方式有两种,一种是直接run Java Application另外一种是通过Spring Boot的Maven插件运行。
第一种:
第二种:
3、测试
方式一:直接在浏览器中输入:localhost:8080/hello 即可访问
方式二:编写测试用例访问:
/**
* Hello World 控制器测试类
* @date 2017年1月26日
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello")
.accept(MediaType.APPLICATION_JSON))//指定响应Content-Type 为JSON格式
.andExpect(status().isOk())//预言响应状态是否OK
.andExpect(content().string(equalTo("Hello World! Welcome to visit waylau.com!")));//预言响应内容是否是"hello world!"
}
}
三、 部署spring boot应用
要部署运行spring boot应用,首选要打包spring boot应用,在pom文件中的spring-boot-maven-plugin插件就是打包spring boot应用的。进入工程目录运行mvn package,如:
D:\cloud-simple-helloword>mvn package
打包过后就可以进入target目录使用java原生命令执行这个应用了。
D:\cloud-simple-helloword\target>java -jar cloud-simple-helloword-0.0.1.jar --server.port=8081
Spring boot提供的一些开箱即用的应用非常容易使用,比如监控,只需要在pom文件中引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
引入之后,spring boot是默认开启监控的,运行应用后可以在浏览器中输入:http://localhost:8080/health 就可以看到默认的监控信息了:
{"status":"UP","diskSpace":{"status":"UP","total":161067397120,"free":91618398208,"threshold":10485760}}
信息包括程序执行状态以及基本的磁盘信息。