Spring Boot是为了简化Spring应用的创建、运行、调试、部署等而出现的,使用它可以做到专注于Spring应用的开发,而无需过多关注XML的配置。
简单来说,它提供了一堆依赖打包,并已经按照使用习惯解决了依赖问题---习惯大于约定。
新建Maven项目,POM文件如下:
<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 。
@EnableAutoConfiguration 用于自动配置。简单的说,它会根据你的pom配置(实际上应该是根据具体的依赖)来判断这是一个什么应用,并创建相应的环境。
在上面这个例子中,@EnableAutoConfiguration 会判断出这是一个web应用,所以会创建相应的web环境。
SpringApplication 则是用于从main方法启动Spring应用的类。
默认访问地址: http://localhost:8080/
Spring Boot在Tomcat中运行
添加servlet-api的依赖
<!--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);
}
经过以上配置,我们把构建好的war包拷到tomcat的webapp下,启动tomcat就可以访问啦
注意点:
1)命名都是约定俗成,不要随便改名字,以及目录结构
2) 要将Application放在最外层,也就是要包含所有子包。
比如你的groupId是com.google,子包就是所谓的com.google.xxx,所以要将Application类要放在com.google包下。
springboot会自动加载启动类所在包下及其子包下的所有组件.
Controller类中的@ResponseBody
表示直接返回内容
浙公网安备 33010602011771号