Spring Boot不是一门新技术, 基于Spring framework。使用“习惯优于配置” , “开箱即用”,
只需要很少的Spring配置,就可构建一套 Web 项目,Restful API项目或者微服务。
动手实践:
创建 Application.java,其注解 @SpringBootApplication 表示这是一个SpringBoot应用,运行其主方法main就会启动tomcat,默认端口是8080
@SpringBootApplication:标识Spring Boot Application Class的Annotation
• 触发Spring的自动配置
• 触发Component Scan自动加载Controller等
main方法中的SpringApplication.run(MyTestApplication.class, args);
就是让MyTestApplication.class跑起来
具体操作:
启动应用服务器 • 选中SimpleApplication ->点击鼠标右键-> 选择Run As -> 选择Java Application
控制台中出现:Tomcat started on port(s): 8080 (http) with context path
package com.example.myTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyTestApplication {
public static void main(String[] args) {
SpringApplication.run(MyTestApplication.class, args);
}
}
接着创建控制器类HelloController, 这个类就是Spring MVC里的一个普通的控制器。
@RestController 是spring4里的新注解,是@ResponseBody和@Controller的缩写。
@RestController:标识Restful API Controller Class的Annotation.
其内方法:
• 接受HTTP Request
• 产生HTTP Response
@GetMapping:标识该方法将接受HTTP Request GET请求。/hello为对象资源的URL
要注意HelloController记得放在Application同一个目录下,就是说将Application类放在上一级包里。比如com.xxx.controller里放控制器,com.xxx里放Application类
如下图 Application类@SpringBootApplication 在控制器@RestController的上级目录
package com.example.myTest.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "Hello Spring Boot!";
}
}
接下来就运行程序, 然后访问地址http://localhost:8080/hello