当前位置: 移动技术网 > IT编程>开发语言>Java > Springboot 系列(一)Spring Boot 入门篇

Springboot 系列(一)Spring Boot 入门篇

2019年02月15日  | 移动技术网IT编程  | 我要评论

注意:本 spring boot 系列文章基于 spring boot 版本 v2.1.1.release 进行学习分析,版本不同可能会有细微差别。

前言

由于 j2ee 的开发变得笨重,繁多的配置,错乱的依赖管理,低下的开发效率,复杂的部署流程,第三方技术的集成难度较大等。同时随着复杂项目的演进,微服务分布式架构思想逐渐进入开发者的视野。

1. spring boot 介绍

spring boot 提供了一组工具只需要极少的配置就可以快速的构建并启动基于 spring 的应用程序。解决了传统 spring 开发需要配置大量配置文件的痛点,同时 spring boot 对于第三方库设置了合理的默认值,可以快速的构建起应用程序。当然 spring boot 也可以轻松的自定义各种配置,无论是在开发的初始阶段还是投入生成的后期阶段。

2. spring boot 优点

  • 快速的创建可以独立运行的 spring 项目以及与主流框架的集成。
  • 使用嵌入式的 servlet 容器,用于不需要打成war包。
  • 使用很多的启动器(starters)自动依赖与版本控制。
  • 大量的自动化配置,简化了开发,当然,我们也可以修改默认值。
  • 不需要配置 xml 文件,无代码生成,开箱即用。
  • 准生产环境的运行时应用监控。
  • 与云计算的天然集成。

3. spring boot 前置

说了那么多的 spring boot 的好处,那么使用 spring boot 需要哪些前置知识呢?我简单列举了一下。

  • spring 框架的使用。
  • maven 构建工具的使用。
  • idea 或其他开发工具的使用。

4. spring boot 体验

现在我们已经了解了 spring boot 是什么,下面我们将使用 spring boot 开发一个入门案例,来体验 spring boot 开发姿势是如何的优雅与迅速。
spring boot 官方已经为我们如何快速启动 spring boot 应用程序提供了多种方式。

你可以在 spring 官方网站直接生成项目下载导入ide进行开发。

https://start.spring.io/

也可以直接克隆 github 上的初始项目进行体验。

git clone https://github.com/spring-guides/gs-spring-boot.git
cd gs-spring-boot/initial

这里我们选择后者,直接克隆进入到 initial 文件夹使用 maven 进行编译启动。

 mvn package && java -jar target/gs-spring-boot-0.1.0.jar

第一次编译需要下载需要的依赖,耗时会比较长,编译完成之后紧接着可以看到 spring 的启动标志。这时 spring boot 的 web程序已经运行在8080端口了。

$ curl -s localhost:8080
greetings from spring boot!

5. spring boot 开发

下面手动编写一个 spring boot 入门案例,快速的开发一个 web mvc 应用。
项目结构如下:

spring boot 项目结构

5.1 依赖项

    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>2.1.1.release</version>
        <relativepath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-test</artifactid>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-maven-plugin</artifactid>
            </plugin>
        </plugins>
    </build>

spring-boot-starter-parent 是spring boot 的核心依赖,它里面定义了各种在开发中会用到的第三方 jar 的版本信息,因此我们在引入其他的 spring boot 为我们封装的启动器的时候都不在需要指定版本信息。如果我们需要自定义版本信息,可以直接覆盖版本属性值即可。

spring-boot-starter-web 提供 web 以及 mvc 和 validator 等web开发框架的支持。

spring-boot-starter-test 提供测试模块的支持。如 junit,mockito。

需要说明的是,spring boot 为我们提供了很多的已经封装好的称为启动器(starter)的依赖项。让我们在使用的时候不需要再进行复杂的配置就可以迅速的进行应用集成。所有的官方启动器依赖可以在这里查看。

所有官方发布的启动器都遵循类似的命名模式; spring-boot-starter-*,这里*是指特定类型的应用程序。此命名结构旨在帮助您寻找启动器。

注意:编写自己的启动器的时候不应该使用这种命名方式。

5.2 启动类

@springbootapplication
public class helloapplication {

    public static void main(string[] args) {
        springapplication.run(helloapplication.class, args);
    }

    @bean
    public commandlinerunner commandlinerunner(applicationcontext ctx) {
        return args -> {
            // 开始检查spring boot 提供的 beans
            system.out.println("let's inspect the beans provided by spring boot:");
            string[] beannames = ctx.getbeandefinitionnames();
            arrays.sort(beannames);
            for (string beanname : beannames) {
                system.out.println(beanname);
            }
        };
    }
}

@springbootapplication 注解是一个便利的注解,它包含了以下几个注解。

  1. @configuration 定义配置类。

  2. @enableautoconfiguration 开启自动配置。

  3. @enablewebmvc 标记为 web应用程序。

  4. @componentscan 组件扫描。

5.3 控制器

@restcontroller
public class hellocontroller {
    @requestmapping("/")
    public string index() {
        return "greetings from spring boot!";
    }
}

@restcontroller@restcontroller@responsebody 的结合体。

5.4 访问测试

直接启动 helloapplication.java 类就可以在控制台看到启动输出,然后访问8080端口查看启动是否正常。

spring boot 项目结构

经过上面的例子,已经使用 spring boot 快速的创建了一个 web 应用并进行了简单的访问测试。

6. spring boot 单元测试

结合上面提到的 spring boot 启动器知识,spring boot 已经为我们提供了丰富的第三方框架,测试框架也不例外。

导入单元测试依赖。

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-test</artifactid>
            <scope>test</scope>
        </dependency>   

6.1 模拟请求测试

编写单元测试

import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.autoconfiguremockmvc;
import org.springframework.boot.test.context.springboottest;
import org.springframework.http.mediatype;
import org.springframework.test.context.junit4.springrunner;
import org.springframework.test.web.servlet.mockmvc;
import org.springframework.test.web.servlet.request.mockmvcrequestbuilders;

import static org.springframework.test.web.servlet.result.mockmvcresultmatchers.content;
import static org.springframework.test.web.servlet.result.mockmvcresultmatchers.status;

/**
 * 单元测试
 */
@runwith(springrunner.class)
@springboottest
@autoconfiguremockmvc
public class helloapplicationtests {

    @autowired
    private mockmvc mvc;

    @test
    public void contextloads() throws exception {
        mvc.perform(mockmvcrequestbuilders.get("/").accept(mediatype.application_json))
                .andexpect(status().isok())
                .andexpect(content().string("greetings from spring boot!"));
    }

}

关于上面代码的一些说明。

  • mockmvc 允许我们方便的发送 http 请求。
  • springboottest 方便的创建一个 spring boot 项目的测试程序。

运行没有任何异常说明程序测试通过。

6.2 spring boot 集成测试

import org.junit.before;
import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import org.springframework.boot.test.web.client.testresttemplate;
import org.springframework.boot.web.server.localserverport;
import org.springframework.http.responseentity;
import org.springframework.test.context.junit4.springrunner;

import java.net.url;

/**
 * <p>
 * 嵌入式服务器由随机端口启动webenvironment = springboottest.webenvironment.random_port
 * 并且在运行时发现实际端口@localserverport
 *
 * @author niujinpeng
 * @date 2018/12/4 15:02
 */
@runwith(springrunner.class)
@springboottest(webenvironment = springboottest.webenvironment.random_port)
public class helloapplicationtestbyspringboot {

    @localserverport
    private int port;

    private url base;

    @autowired
    private testresttemplate template;

    @before
    public void setup() throws exception {
        this.base = new url("http://localhost:" + port + "/");
    }

    @test
    public void gethello() throws exception {
        responseentity<string> response = template.getforentity(base.tostring(), string.class);
        assert (response.getbody().equals("greetings from spring boot!"));
    }

}

嵌入式服务器由随机端口启动 webenvironment = springboottest.webenvironment.random_port

并且在运行时使用注解 @localserverport 发现实际端口。

运行测试类通过输出。

2018-12-06 22:28:01.914  info 14320 --- [o-auto-1-exec-1] o.a.c.c.c.[tomcat].[localhost].[/]       : initializing spring dispatcherservlet 'dispatcherservlet'
2018-12-06 22:28:01.914  info 14320 --- [o-auto-1-exec-1] o.s.web.servlet.dispatcherservlet        : initializing servlet 'dispatcherservlet'
2018-12-06 22:28:01.937  info 14320 --- [o-auto-1-exec-1] o.s.web.servlet.dispatcherservlet        : completed initialization in 23 ms

文章代码已经上传到 github spring boot 入门案例

<完>
本文原发于个人博客: 转载请注明出处

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网