什么是springboot
Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。用我的话来理解,就是 Spring Boot 其实不是什么新的框架,它默认配置了很多框架的使用方式,就像 Maven 整合了所有的 Jar 包,Spring Boot 整合了所有的框架。Spring Boot让我们的Spring应用变的更轻量化。比如:你可以仅仅依靠一个Java类来运行一个Spring引用。你也可以打包你的应用为jar并通过使用java -jar来运行你的Spring Web应用。
springboot的优点
为所有Spring开发者更快的入门
开箱即用,提供各种默认配置来简化项目配置
内嵌式容器简化Web项目
没有冗余代码生成和XML配置的要求
Maven构建springboot项目
1.通过https://start.spring.io/创建springboot项目
点击 Generate Project 下载项目压缩包,解压压缩包后,用idea导入,选择maven一路next即可。
2.用IDEA直接创建springboot项目:
打开IDEA,点击Create New Project,选择Spring Initializr
点击next,填写对应的项目名,包名等next
选择要导入的依赖,如web依赖:
pom文件引入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<!—SpringBoot web 组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
spring-boot-starter-parent作用
在pom.xml中引入spring-boot-start-parent,spring官方的解释叫什么stater poms,它可以提供dependency management,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了,后面可以看到。
spring-boot-starter-web作用
springweb 核心组件
pom.xml文件中默认有两个模块
spring-boot-starter:核心模块,包括自动配置支持、日志和YAML;
spring-boot-starter-test:测试模块,包括JUnit、Hamcrest、Mockito。
编写controller内容
@RestController
public class HelloController {
@RequestMapping("hello")
String hello() {
return "Hello World!";
}
}
@RestController=@Controller+@ResponBody,意思就是controller里面的方法都以json格式输出
启动SpringApplication主程序,打开浏览器访问http://localhost:8080/hello,就可以看到效果了
开发环境的调试
热启动在正常开发项目中已经很常见了吧,虽然平时开发 web 项目过程中,改动项目启重启总是报错;但 Spring Boot 对调试支持很好,修改之后可以实时生效,需要添加以下的配置:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
IDEA配置:
当我们修改了Java类后,IDEA默认是不自动编译的,而spring-boot-devtools又是监测classpath下的文件发生变化才会重启应用,所以需要设置IDEA的自动编译:
1.勾选File-Settings-Compiler-Build Project automatically
2.ctrl + shift + alt + /,选择Registry,勾上 Compiler autoMake allow when app running
测试
- 修改类–>保存:应用会重启
- 修改配置文件–>保存:应用会重启
- 修改页面–>保存:应用不会重启,但会重新加载,页面会刷新(原理是将spring.thymeleaf.cache设为false,参考:Spring Boot配置模板引擎)