Spring Boot是爲了簡化Spring應用的建立、運行、調試、部署等而出現的,使用它能夠作到專一於Spring應用的開發,而無需過多關注XML的配置。php
簡單來講,它提供了一堆依賴打包,並已經按照使用習慣解決了依賴問題---習慣大於約定。java
新建Maven項目,POM文件以下:web
<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>cn.larry.spring</groupId> <artifactId>larry-spring-demo4</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
保存pom,刷新maven,以便刷新依賴導入。
基本上,若是沒有特別的須要,如今就能夠直接寫Controller了!!!
package cn.larry.spring.controller; 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; @Controller @EnableAutoConfiguration public class SampleController { @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(SampleController.class, args); } }
這裏有兩個新東西:@EnableAutoConfiguration 和 SpringApplication 。spring
@EnableAutoConfiguration 用於自動配置。簡單的說,它會根據你的pom配置(實際上應該是根據具體的依賴)來判斷這是一個什麼應用,並建立相應的環境。apache
在上面這個例子中,@EnableAutoConfiguration 會判斷出這是一個web應用,因此會建立相應的web環境。api
SpringApplication 則是用於從main方法啓動Spring應用的類。tomcat
默認訪問地址: http://localhost:8080/springboot
Spring Boot在Tomcat中運行app
添加servlet-api的依賴webapp
<!--Springboot集成的tomcat來提供api-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
新建一個啓動類
@SpringBootApplication // mapper 接口類掃描包配置 public class Application extends SpringBootServletInitializer{ public static void main(String[] args) throws IOException { // 程序啓動入口 Properties properties = new Properties(); InputStream in = Application.class.getClassLoader().getResourceAsStream("app.properties"); properties.load(in); SpringApplication app = new SpringApplication(Application.class); app.setDefaultProperties(properties); app.run(args); /*EmbeddedServletContainerAutoConfiguration*/ } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { // TODO Auto-generated method stub builder.sources(this.getClass()); return super.configure(builder); }
注意點:
1)命名都是約定俗成,不要隨便更名字,以及目錄結構
2) 要將Application放在最外層,也就是要包含全部子包。
好比你的groupId是com.google,子包就是所謂的com.google.xxx,因此要將Application類要放在com.google包下。
springboot會自動加載啓動類所在包下及其子包下的全部組件.
Controller類中的@ResponseBody
表示直接返回內容