1. 程式人生 > >Spring Boot學習(三)

Spring Boot學習(三)

src pack art tin pre size -s script jar

Spring boot實戰 —— Hello Word

1、創建maven項目

2、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.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description
> <!--spring boot父依賴--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository
--> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <!--Java版本--> </properties> <dependencies> <!--Spring Boot web支持--> <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> <!--maven插件--> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

3、DemoApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication /*核心配置,是Spring Boot應用的標識*/
public class DemoApplication {

    /*main方法:應用入口*/
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

4、HelloController.java——Controller層

@RestController
public class HelloController {

    @RequestMapping(value = "hello",method = RequestMethod.GET)
    public String index(){
        return "Hello World";
    }
}

@RestController:相當於@Controller與@ResponseBody的組合

@RequestMapping:提供路由信息。上面的代碼可以替換成@GetMapping("hello")

5、application.yml

設置該應用的端口為8080

server:
  port: 8080

6、運行

訪問地址:http://127.0.0.1:8080/hello

技術分享

Spring Boot學習(三)