养浩然之气,做博学之人
spring boot 致力于简洁,简化配置(即繁琐的xml配置),程序能够更快的运行和启动。它是下一代javaweb框架,并且它是spring cloud(微服务)的基础。
一个顺手的Java 开发IDE(Eclipse或Idea Intellij)
Java环境(JDK 1.8或以上版本)
Maven 3.0+
选择webapp项目
具体可参考:创建Maven项目Eclipse方式
在Maven项目依赖中引入spring-boot-starter-web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>1.5.3.RELEASE</version> </dependency>
然后在pom文件中右击选择maven中reimport从仓库下载依赖,建议使用阿里云的中央仓库,可以通过更改Maven的settings文件指定中央仓库。
创建Spring Boot启动类:
package com.xiaowangyun.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; /*** * @author 小北 * SpringBoot 启动入口 * 20180805 * www.xiaowangyun.com */ @SpringBootApplication @EnableAutoConfiguration public class DemoApplication { public static void main(String argv[]){ SpringApplication.run(DemoApplication.class,argv); } }
创建测试控制器:
package com.xiaowangyun.demo.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; //等同于同时加上了@Controller和@ResponseBody @RestController public class IndexController { //访问/hello或者/test,都会返回HelloWord @RequestMapping(value = {"/hello","/test"},method = RequestMethod.GET) public String HelloWorld(){ return "Hello World!!!"; } }
运行应用:mvn spring-boot:run或在IDE中运行main()方法,在浏览器中访问http://localhost:8080/hello,Hello World!就出现在了页面中。只用了区区十几行Java代码,一个Hello World应用就可以正确运行了。
SpringApplication是Spring Boot框架中描述Spring应用的类,它的run()方法会创建一个Spring应用上下文(Application Context)。另一方面它会扫描当前应用类路径上的依赖,例如本例中发现spring-webmvc(由 spring-boot-starter-web传递引入)在类路径中,那么Spring Boot会判断这是一个Web应用,并启动一个内嵌的Servlet容器(默认是Tomcat)用于处理HTTP请求。
Spring WebMvc框架会将Servlet容器里收到的HTTP请求根据路径分发给对应的@Controller类进行处理,@RestController是一类特殊的@Controller,它的返回值直接作为HTTP Response的Body部分返回给浏览器。
@RequestMapping注解表明该方法处理那些URL对应的HTTP请求,也就是我们常说的URL路由(routing),请求的分发工作是有Spring完成的。例如上面的代码中http://localhost:8080/根路径就被路由至greeting()方法进行处理。如果访问http://localhost:8080/hello,则会出现404 Not Found错误,因为我们并没有编写任何方法来处理/hello请求。
参考:
https://www.jb51.net/article/133349.htm
https://www.imooc.com/video/13590
https://blog.csdn.net/weixin_40609804/article/details/79037156
编辑:孙小北
本文地址: https://www.xiaowangyun.com/wyblog/detail/?id=218
版权归属: www.xiaowangyun.com 转载时请以链接形式注明出处
0 条评论