深入实践Spring Boot1.3.2 一个简单的实例

    xiaoxiao2024-05-23  113

    1.3.2 一个简单的实例

    Spring Boot的官方文档中提供了一个最简单的Web实例程序,这个实例只使用了几行代码,如代码清单1-3所示。虽然简单,但实际上这已经可以算作是一个完整的Web项目了。

    代码清单1-3 Spring Boot简单实例

    package springboot.example;

     

    import org.springframework.boot.SpringApplication;

    import org.springframework.boot.autoconfigure.SpringBootApplication;

    import org.springframework.web.bind.annotation.RequestMapping;

    import org.springframework.web.bind.annotation.RestController;

     

    @SpringBootApplication

    @RestController

    public class Application {

        @RequestMapping("/")

        String home() {

            return "hello";

        }

     

        public static void main(String[] args) {

            SpringApplication.run(Application.class, args);

        }

    }

    这个简单实例,首先是一个Spring Boot应用的程序入口,或者叫作主程序,其中使用了一个注解@SpringBootApplication来标注它是一个Spring Boot应用,main方法使它成为一个主程序,将在应用启动时首先被执行。其次,注解@RestController同时标注这个程序还是一个控制器,如果在浏览器中访问应用的根目录,它将调用home方法,并输出字符串:hello。

    1.4 运行与发布

    本章实例工程的完整代码可以使用IDEA直接从GitHub的https://github.com/chen-fromsz/spring-boot-hello.git中检出,如图1-15所示,单击Clone按钮将整个项目复制到本地。

     

    图1-15 检出实例工程

    相关资源:《深入实践SpringBoot》
    最新回复(0)