SpringBoot入门之零基础搭建web应用

引言

之前也没有深入学习过spring框架,最近SpringBoot流行起来后想补下这方面的知识,于是照着SpringBoot官网上的英文教程开始helloworld入门,踩到几个小坑,记录下学习流程。

SpringBoot有哪些优点

SpringBoot可以帮助我们快速搭建应用,自动装配缺失的bean,使我们把更多的精力集中在业务开发上而不是基础框架的搭建上。它有但是远不止以下这几点优点:

  • 它有内置的Tomcat和jetty容器,避免了配置容器、部署war包等步骤
  • 能够自动添加缺失的bean
  • 简化了xml配置甚至不需要xml来配置bean

入门准备工作

  • JDK1.8+(JDK1.7也可以,但是官方的例程里用到了一些lambda表达式,lambda表达式只在JDK1.8及以上的版本才支持)
  • MAVEN 3.0+
  • IDE:IDEA (开发工具我选择的是IDEA)

搭建HelloWorld web应用

创建一个空maven工程

使用idea创建maven工程,这里GroupId和artifactId任意指定即可

创建maven工程

我们开始配置pom文件,指定该helloworld的父工程为spring-boot-starter-parent,这样我们就不需要指定SpringBoot的一些相关依赖的版本了(因为在父工程中已指定)。
配置完的pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

其中spring-boot-maven-plugin插件可以帮助我们在使用mvn package命令打包的时候生成一个可以直接运行的jar文件。(spring-boot-maven-plugin作用)

创建web应用

创建一个controller,目录在src/main/java/hello/HelloController.java

package hello;

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

/**
 * @author zengrong.gzr
 * @Date 2017/03/11
 */
@RestController
public class HelloController {
    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

    @RequestMapping("/HelloWorld")
    public String hello() {
        return "Hello World!";
    }
}

创建一个web application,目录在src/main/java/hello/HelloController.java

package hello;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * @author zengrong.gzr
 * @Date 2017/03/11
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    //指定下bean的名称
    @Bean(name = "gzr")
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                System.out.println("Let's inspect the beans provided by Spring Boot:");
                String[] beanNames = ctx.getBeanDefinitionNames();
                for (String beanName : beanNames){
                    System.out.println(beanName);
                }
            }
        };
    }
}

可以看到,我们不需要xml来配置bean,也不需要配置web.xml文件,这是一个纯java应用,我们不需要来处理复杂的配置关系等。

运行应用

可以通过命令行直接运行应用
$ mvn package && java -jar target/helloworld-1.0-SNAPSHOT.jar

当然我更倾向于使用idea来运行,这样可以debug看到SpringBoot的初始化过程,配置过程如下
idea运行app
让我们用idea来debug看看,如果编译时出现“Error:java: Compilation failed: internal java compiler error”的错误(如下图),我们需要修改idea默认的编译器设置
compile错误.png
修改compiler设置如下
compiler修改

我们可以在控制台看到运行结果,截取一段见下图,可以看到打印出的bean,包括helloController、和我们指定名字的gzr等
打印出的bean.png

下面我们来检查web的服务,在命令行运行

$ curl localhost:8080
Greetings from Spring Boot!
$ curl localhost:8080/HelloWorld
Hello World!%

服务正常运行~

添加测试用例

我们先在pom中添加测试需要的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

添加一个简单的测试用例,目录在src/test/java/hello/HelloControllerTest.java

package hello;

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.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author zengrong.gzr
 * @Date 2017/03/11
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
    }
}

可以很轻松地直接运行该test

至此我们模拟了http请求来进行测试,通过SpringBoot我们也可以编写一个简单的全栈集成测试:
src/test/java/hello/HelloControllerIT.java

package hello;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * @author zengrong.gzr
 * @Date 2017/03/11
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {

    @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);
        assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
    }
}

通过webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT我们可以让内置的服务器在随机端口启动。

添加生产管理服务

通常我们在建设网站的时候,可能需要添加一些管理服务。SpringBoot提供了几个开箱即用的管理服务,如健康检查、dump数据等。
我们首先在pom中添加管理服务需要的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

直接运行程序,可以看到控制台输出诸多SpringBoot提供的管理服务
SpringBoot提供的管理服务.png
我们可以很方便地检查app的健康状况

$ curl localhost:8080/health
{"status":"UP"}
$ curl localhost:8080/dump
{"timestamp":1489226509796,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource.","path":"/dump"}

当我们执行curl localhost:8080/dump可以看到返回状态为“Unauthorized”,dump、bean等权限需要关闭安全控制才可以访问。那么如何关闭?可以通过注解的方式,也可以通过配置application.properties的方式。

这里我们选择第二种,在src/main/resources文件夹下新建application.properties文件(框架会自动扫描该文件),在文件中添如配置management.security.enabled=false即可。

启动应用后,我们再运行curl localhost:8080/beans命令,可以看到命令行打印出系统加载的所有bean。

源码下载

附上源码

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值