- 创建Maven项目
- 添加springBoot的起步依赖
SpringBoot要求,项目要继承SpringBoot的起步依赖spring-boot-starter-parent<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath/> </parent>
<relativePath/>
设定空值将始终从仓库中获取,不从本地路径获取,如果不加此元素标签,在创建过程中可能会有报错问题。
SpringBoot要集成SpringMVC进行Controller的开发,所以项目要导入web的启动依赖<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
- 编写SpringBoot引导类
关于SpringBoot引导类:@SpringBootApplication public class MySpringbootApplication { public static void main(String[] args) { SpringApplication.run(MySpringbootApplication.class); } }
1. 使用SpringApplication类中的run静态方法,run方法表示运行SpringBoot的引导类,参数为SpringBoot引导类的字节码对象。
2. 添加注解@SpringBootApplication,声明该类是SpringBoot的引导类 - 运行测试完成结果
- 编写Controller
在引导类MySpringBootApplication同级包或者子级包中创建Controller类
关于Controller类:@Controller public class UserController { @RequestMapping("/test") @ResponseBody public Map test(){ Map map = new HashMap(); map.put("1","Hello World"); return map; } }
使用方法与Spring MVC中基本相同:
1. 在类上使用“@Controller”注解修饰;
2. 在方法使用RequestMapping()注解指定URI地址;
3. 为了方便前后端分离,使用@ResponseBody传递Json对象。
使用浏览器访问: