从零开始的Spring Boot (一)
What is Spring boot?
关于Spring Boot的说明直接看官网的比较准确,因此不多赘述,Spring Boot的出现我认为属于是SpringMVC的配置简化版,也就是约定大于配置(个人这么认为)免去了SpringMVC开发时候的一大堆的配置,官方说法 “just run”!。不多说,直接开始。
HelloWorld!
环境:eclipse + maven + jdk1.8
创建一个Maven项目
这里直接选择Create a simple project,下一步,finish就行了。
- pom.xml导入Spring Boot依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- Spring Boot 启动父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<!-- Spring Boot web模块 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 为了使用jdk1.8加入此项配置 maven默认使用1.5版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 创建HelloWorld.Java
package helloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@EnableAutoConfiguration
@Controller
public class HelloWorld {
@RequestMapping("/hello")
public @ResponseBody String sayHello(){
return "hello world";
}
public static void main(String args[]){
SpringApplication.run(HelloWorld.class, args);
}
}
这里的@EnableAutoConfiguration很明显是让SpringBoot自动配置的意思。SpringBoot会根据pom导入的包尽可能的判断我们想要干什么从从而自动的配置。@Controller声明这是一个Controller,最后加上@ResponseBody注解返回json数据方便页面上显示。
- 运行HelloWorld.java(run as java application), 启动完成后打开浏览器输入localhost:8080/hello/
至此一个简单的helloworld就完成了。
Question?
- spring-boot-starter-web都有些什么包?
- 服务器?
可以看到其中包含了springboot的包,springMVC中常见的webmvc,aop,jackson等熟悉的包,tomcat包以及日志包。说白了spring-boot-starter-web也就是个集中营压缩包的感觉。
在看看官方说明:
- 可以看出springboot内嵌了tomcat,jetty,Undertow(JBoss下的一款服务器)。
并且springboot默认使用的是tomcat作为服务器,如果想要切换jetty或者Undertow的话只需要修改pom文件即可(自动配置)。
很简单,先排除spring-boot-starter-web中的tomcat组件再导入jetty或者Undertow的包即可.(以jetty为例)
- 可以看出springboot内嵌了tomcat,jetty,Undertow(JBoss下的一款服务器)。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
</dependencies>