1、基礎項目構建,引入web模塊,完成一個簡單的RESTful API

1、Spring Boot的主要優勢:java

  • 爲全部Spring開發者更快的入門
  • 開箱即用,提供各類默認配置來簡化項目配置
  • 內嵌式容器簡化Web項目
  • 沒有冗餘代碼生成和XML配置的要求

 

2、使用maven構建項目web

1.訪問官網:http://start.spring.io/  選擇基本的構建工具。spring

2.點擊Generate Project下載項目壓縮包。apache

3.解壓項目包,並用ecplise以Maven項目導入瀏覽器

  1. 菜單中選擇File–>New–>Project from Existing Sources...
  2. 選擇解壓後的項目文件夾,點擊OK
  3. 點擊Import project from external model並選擇Maven,點擊Next到底爲止。
  4. 若你的環境有多個版本的JDK,注意到選擇Java SDK的時候請選擇Java 7以上的版本

 

 3、項目結構解析springboot

經過上面步驟完成了基礎項目的建立,Spring Boot的基礎結構共三個文件(具體路徑根據用戶生成項目時填寫的Group全部差別):mvc

  • src/main/java下的程序入口:Chapter1Application
  • src/main/resources下的配置文件:application.properties
  • src/test/下的測試入口:Chapter1ApplicationTests
package com.didispace;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

@SpringBootApplication
public class Chapter1Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Chapter1Application.class, args);
    }
    @Override//爲了打包springboot項目
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }
}
Chapter1Application
server.port=8080
application.properties
package com.didispace;

import com.didispace.web.HelloController;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

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;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class Chapter1ApplicationTests {

    private MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World")));
    }

}
Chapter1ApplicationTests

生成的Chapter1ApplicationChapter1ApplicationTests類均可以直接運行來啓動當前建立的項目,因爲目前該項目未配合任何數據訪問或Web模塊,程序會在加載完Spring以後結束運行。app

 

4、引入web模塊maven

當前的pom.xml內容以下,僅引入了兩個模塊:ide

  • spring-boot-starter:核心模塊,包括自動配置支持、日誌和YAML
  • spring-boot-starter-test:測試模塊,包括JUnit、Hamcrest、Mockito
<?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>com.didispace</groupId>
    <artifactId>Chapter1</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>Chapter1</name>
    <description>The first Spring Boot project</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

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

    </dependencies>
    
    <build>
        <defaultGoal>compile</defaultGoal>
        <sourceDirectory>src</sourceDirectory>
        <finalName>springboot-package</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.didispace.Chapter1Application</mainClass> 
                    <skipTests>true</skipTests> 
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>                
            </plugin>

        </plugins>
    </build>

</project>
pom.xml

 

5、編寫服務

package com.didispace.web;

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

@RestController
public class HelloController {

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

}
HelloController

 啓動主程序,打開瀏覽器訪問http://localhost:8080/hello,能夠看到頁面輸出Hello World

 

6、編寫單元測試用例

package com.didispace;

import com.didispace.web.HelloController;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

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;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class Chapter1ApplicationTests {

    private MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World")));
    }

}
Chapter1ApplicationTests
相關文章
相關標籤/搜索