SpringBoot 快速入门

1、什么是 SpringBoot

  随着动态语言的流行,例如:Ruby、Groovy、Scala、Node.js,Java 的开发显得格外的笨重:

    繁多的配置、低下的开发效率、复杂的部署流程以及第三方技术集成难度大。

  在上述环境下,SpringBoot 应运而生。它使用“习惯由于配置”的理念让你的项目快速运行起来(项目中存在大量的配置,此外还内置一个习惯性的配置,让你无须手动进行配置)。

  使用 SpringBoot 很容易创建一个独立运行(运行 jar 且内嵌 Servlet 容器)、准生产级别的基于 Spring 框架的项目,使用 SpringBoot 你可以不用或者只需要很少的 Spring 配置。

2、SpringBoot 优缺点

  优点

  1. 快速构建项目

  2. 对主流开发框架的无配置集成

  3. 项目可独立运行,无须外部依赖 Servlet 容器

  4. 提供运行时的应用监控

  5. 极大地提高了开发、部署效率

  6. 与云计算的天然集成

  缺点

  1. 书籍文档较少且不够深入

3. 快速入门

  1. 设置 SpringBoot 的 parent

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
  </parent>

   说明:SpringBoot 的项目必须要将 parent 设置为 spring boot 的 parent,该 parent 包含了大量默认的配置,大大简化了我们的开发。例如包含:cache、ElasticSearch、gson、http、jackson、jdbc、jmx、kafka、logging、mail。mongo、quartz、security、solr、web、webservice、websocket 等。

  2. 导入 SpringBoot 的 web 支持

     <!-- 用于 spring-boot web 组件 -->
      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

   说明:这个组件导入默认内嵌入一个 tomcat 容器,这样在你启动的时候无须自己再外部引入。

  3. 添加 SpringBoot maven 插件

    <build>
        <!-- springboot maven 插件 -->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

   4. 编写第一个 SpringBoot 的应用

  @Controller
  @SpringBootApplication
  @Configuration
  public class HelloApplication {
     @RequestMapping("hello")
     @ResponseBody
     public String hello(){
        return "hello world!";
     }
    
     public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
     }
  }

  代码说明:

  1、@SpringBootApplication:SpringBoot 项目的核心注解,主要目的是开启自动配置;

  2、@Configuration:这是一个配置 Spring 的配置类;

  3、@Controller:标明这是一个 SpringMVC 的 Controller 控制器;

  4、@RequestMapping("hello"):用于标识请求导航路径

  5、@ResponseBody:用于标识请求返回 body 体内容

  6、main方法:在main方法中启动一个应用,即:这个应用的入口;

  5、启动应用

  在Spring Boot项目中,启动的方式有两种,一种是直接run Java Application另外一种是通过Spring Boot的Maven插件运行。

  

猜你喜欢

转载自www.cnblogs.com/liang1101/p/9138938.html