万事开头难,只要会写Helloworld就成功了一半,下面就来一起学习怎么用SpringBoot来写Helloworld
springboot实现MVC简直是太简单了,堪称零配置,不信来看下面代码
package com.shx.action;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by admin on 2017/7/28.
*/
@RestController
public class HelloWorldAction {
@RequestMapping(value = "hello")
public String helloworld(){
return "helloworld";
}
}
目录结构如下:
没有任何配置,只需要一个@RestController注解轻松实现
启动项目,访问http:localhost:8080/hello就能得到你想要的了,没错就是这么简单!
下面来介绍一下这几个文件
DemoApplication
工程主入口,暂且先不管它是干什么的
application.properties
配置文件,任何配置都可以往这里边加试着加入下面一句配置然后重启应用
server.port=8088控制台会输出类似下面这样的语句
Tomcat started on port(s): 8088 (http)
然后在浏览器访问原来的8080端口就不能访问了,改成8088,期望的helloworld又出现了,如此简单就把端口号改了
细心的同学应该能发现他下面有很多可以配置的属性,用到的时候我们在慢慢研究
HelloWorldAction
这想必就不用多说了,我们用spring的时候再熟悉不过了,这跟以前没有什么差别,说下这个@RestController注解吧,spring官网这么说
The @RestController
and @RequestMapping
annotations are Spring MVC annotations (they are not specific to Spring Boot). See the MVC section in the Spring Reference Documentation for more details.
这不是Spring Boot的注解,Spring MVC以前就有, @RestController是@Controller和@ResponseBody的结合体