Spring Boot 第一个RESTful 服务

2018-01-11  本文已影响19人  王不哈

1. 创建 Maven 工程

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

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

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. 编写一个Demo

@RestController
@RequestMapping(value = "/")
public class HelloController {
    @RequestMapping(value = "hello", method = RequestMethod.GET)
    public String hello() {
        return "Hello World";
    }
}
package com.llscz.datejiang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class DateJiangApplication {

    public static void main(String[] args) {
        SpringApplication.run(DateJiangApplication.class, args);
    }
}

3. 运行 & 部署

  1. Spring Boot 可当作一个普通应用程序启动,内嵌了一个Web容器。
  2. 使用 mvn clean package 命令生成一个可执行的jar包,然后使用命令 java -jar 文件名 启动应用。

需要在 pom.xml 中添加如下内容:

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


上一篇 下一篇

猜你喜欢

热点阅读