在上一篇中,我们完成了第一个helloWorld的例子,算是简单体验了一次SpringBoot的魅力,而在开始接下来的学习前,我们先规范一下自己的代码。
代码约定
作为代码开发,肯定是要遵守一定的代码约定及规范,现在回过头来看我们上一篇中的代码:
@SpringBootApplication
@RestController
public class BootStrapApplication {
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(){
return "hello,it is successful";
}
public static void main(String[] args) {
SpringApplication.run(BootStrapApplication.class,args);
}
}
如果我们再有其他方法,继续在该代码上继续添加吗,显然不是。我们在SpringMVC写代码时,MVC三层结构划分很清楚,在学习软件架构的时候,也会一直听到“高内聚,低耦合”这句话。而在SpringBoot里,我们也主张这么来做,每个SpringBoot程序都有一个启动程序,这个启动程序就是代码中的main方法。所以我们应该将这个启动类单独来写,该类只管启动SpringBoot程序,不管业务代码。所以我们新建一个Chapter1Controller类,将接口访问代码提取出来
@RestController
@RequestMapping(value = "/chapter_1")
public class Chapter1Controller {
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(){
return "hello,it is successful";
}
}
BootStrapApplication代码如下
@SpringBootApplication
public class BootStrapApplication {
public static void main(String[] args) {
SpringApplication.run(BootStrapApplication.class,args);
}
}
这样是不是代码结构看着更清晰呢,哈哈。以后每一篇博客,都将会对应一个chapter文件夹,以方便内容及代码应对。
最后按照惯例,附上项目结构
项目地址:https://github.com/Willem520/spring-boot-learning.git,源码位于chapter_1文件夹下。