1. 程式人生 > >SpringBoot搭建微服務(一)HelloWorld!

SpringBoot搭建微服務(一)HelloWorld!

1.建立專案,寫pom.xml

使用maven構建專案後,寫依賴檔案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>com.breeze</groupId> <artifactId>helloworld</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId
>
spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> <relativePath/> </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-web</artifactId> <version>1.3.5.RELEASE</version> </dependency> <!--這個gson包是用於讓返回資料為json格式的--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.3.2.RELEASE</version> </plugin> </plugins> </build> </project>

2.寫main函式還有controller

專案結構如下:
這裡寫圖片描述
Application內容如下:

package com.breeze.helloworld.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by Breeze on 2016/12/14.
 */
 //這個ComponentScan的作用是去掃描controller,並把各個函式的url對映起來
@ComponentScan("com.breeze.helloworld")
//這句是配置當前專案的
@SpringBootApplication
public class Application {
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class,args);
    }
}

Controller裡的內容如下:

package com.breeze.helloworld.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Breeze on 2016/12/14.
 */
 //使當前的類作為Controller
@Controller
public class HelloController {
    //ResponseBody是使用剛才新增的gson依賴讓這個函式返回的內容格式為json
    @ResponseBody
    //對映的url
    @RequestMapping("/hello")
    public String hello()
    {
        return "helloWorld";
    }
}

3.執行效果

這裡寫圖片描述
是不是效果還不錯,搭建起來一個簡單的伺服器的效率還是很高的。