SpringBoot是基于Spring框架的,它的出现极大的简化了spring应用开发,开箱即用,使开发者可以无需过多关注XML配置,很多原先需要的配置都注解化了。这里简单记录一个demo。
1.创建maven项目。
spring-boot集成了大量第三方库配置,提供了一系列的依赖包,这需要maven的支持。
创建完maven后配置pom.xml,父模块为spring-boot-starter-parent。配置starter模块,starter模块包含了spring-boot预定义的一些依赖,其中spring-boot-starter-web包含了web开发的一些常用依赖。如下:
<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>
2.编写controller。
是的,不需要跟原先springmvc一样有繁杂的配置,可以直接开始写controller了(内心os:这也太爽了吧…)
@Controller
@EnableAutoConfiguration //自动配置注解,根据pom配置,判断这是什么应用,并创建相应的环境
public class SampleController {
@RequestMapping("/")
@ResponseBody
String home(){
return "Hello World";
}
/**
* SpringApplication用于从main方法启动Spring应用的类,默认执行步骤如下:
*1.创建一个合适的ApplicationContext实例(取决于classpath)
* 2.注册一个CommandLinePropertySource,以便将命令行参数作为Spring properties。
* 3.刷新application context,加载所有单例beans。
* 4.激活所有CommandLineRunner beans
* @param args
*/
public static void main(String[] args){
SpringApplication.run(SampleController.class,args);
}
}
直接运行main方法,就可以了,到这里就算是成功运行了一个springboot的demo了,浏览器输入: http://localhost:8080/ 就可以访问了。