1. 程式人生 > 其它 >【SpingBoot學習筆記】SpingBoot之helloworld

【SpingBoot學習筆記】SpingBoot之helloworld

    雖然已經參與SpringBoot專案快兩個年頭,像大家一樣,每天忙於開發新功能和修改bug,確實也做了不少核心功能,但能靜下新來從基礎開始學習的機會一直很少,不找藉口,一個原因是忙,一個是懶。。。

造成的結果就是即使寫了再多的業務模組,對於提升開發動手也沒有任何幫助,而且專案中用到的基本都是公司已搭建好的基礎平臺,要求開發人員更傾向於業務模組開發,其實需要我們自己動手搭建或改造平臺的機會少之又少,當有時候需要自己改造一些平臺基礎配置時,會手忙腳亂,各位請吸取我的教訓,當你感覺工作到達瓶頸時,不妨靜下心重新來學一學基礎,一定也會有所收穫。

SpingBoot之helloworld

一.開啟Idea工具,新建maven專案helloworld

二.修改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.test</groupId>
<artifactId>helloword</artifactId>
<version>1.0-SNAPSHOT</version>

<!--手動引入SpringBoot父級依賴-->

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

<!--手動引入web專案依賴-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

<!--手動引入編譯構建外掛-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin </artifactId>
</plugin>
</plugins>
</build>
</project>

三.建立啟動類

package com.test;

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

@SpringBootApplication
public class MySpringBootApplication {

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

} 

 注意,啟動類需要放在包目錄下,不能直接放在java目錄下,否則會報錯,啟動類類名可自定義,除過類名,其他為標準寫法,可直接照搬。

四.建立HelloWorldRestController類

需要新增@RestController註解,不配置method型別時,使用post或get請求都可以,因此可直接使用瀏覽器來測試

package com.test.webservice;

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

@RestController
public class HelloWorldRestController {

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

五.啟動並訪問

啟動專案後日志如下

開啟瀏覽器,輸入http://localhost:8080/檢視結果

也可以指定請求型別為POST

package com.test.webservice;

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

@RestController
public class HelloWorldRestController {

    @RequestMapping(value = "/",method = RequestMethod.POST)
    public String hello(){
        return	"Hello	world!";
    }
}

 此時只能用POST方式訪問,否則報錯,開啟Postman

 GET方式訪問(報錯)

修改為post請求,可正常訪問

此示例來源於加的學習群中發的PDF資料上的,POM檔案引入了Spring Boot應用的父級依賴spring-boot-starter-parent,而不是單獨引入所用的jar包,作為初學者就比較方便了,當然對於大佬來說,熟悉每個包的作用,可自己選擇性的寫依賴,而不是這麼一股腦全部引入。