spring-boot编写控制器
前面加入了spring-boot-starter-web模块,默认集成了spring mvc。因此编写一个controller。即可实现一个简单的hello world程序。
代码如下:
@Controller public class MyController { @GetMapping("/hello") @ResponseBody public String hello() { return "Hello World!"; } }
在代码中,使用了
@Controller注解来修饰MyController,由于上一篇中启动类中使用了@SpringBootApplication注解 该注解具有@ComponentScan的功能。 因此,@Controller会被扫描并注册, 在hello方法中使用了@GetMapping与@ResponseBody注解, 以声明hello方法的访问地址及返回内容; 地址: http://localhost:8080/hello 则可以看到控制器的返回内容。
到此为止,一个spring-boot-web程序已经完成了,整个过程非常简单,大家可以看到,
使用spring boot会,节省了搭建项目框架的时间,
spring boot starter提供了“一站式”的服务,帮助我们开发web应用。
每天进步一点