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
表示直接返回内容