第一個簡單的Spring Boot實例——Hello World

創建一個簡單的Spring Boot項目。該項目的文件結構如下所示:
在這裏插入圖片描述

1、創建一個maven工程。

2、導入spring boot相關的依賴。

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.learnspringboot</groupId>
    <artifactId>spring-boot-01-helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

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

3、編寫一個主程序用於啓動Spring Boot應用。

HelloWorldMainApplication.java

package com.learn;

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

@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) {

        //Spring應用啓動
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }

}

4、編寫相關的Controller和Service。

HelloController.java

package com.learn.controller;

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

@Controller
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "hello world!!!";
    }
}

到此項目就已經構建完成,現在開始運行主函數。
在這裏插入圖片描述
這樣表示服務器運行成功,我們登錄localhost:8080/hello看看結果。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章