天天看點

springboot學習-搭建第一個springboot應用

準備:

idea2017、jdk1.8、springboot2.0.3

首先,建立工程,選擇Spring Initializr,點選next

springboot學習-搭建第一個springboot應用
第二步填寫Group及Artifact:
springboot學習-搭建第一個springboot應用
第三步,勾選 Dependencies,選擇web:
springboot學習-搭建第一個springboot應用
最後點選下一步,直到完成建立項目,此時可以将我們暫時用不到的檔案删除,如圖:
springboot學習-搭建第一個springboot應用
項目建立成功,我們運作Bootdemo01Application,可以看到成功啟動了預設的8080端口:
springboot學習-搭建第一個springboot應用
但在浏覽器輸入localhost:8080時會出現錯誤頁面,這是因為我們還沒有寫任何controller,我們建立一個controller,使得在浏覽器上展示一些東西

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

/**
* Created by 57783 on 2018/7/4.
*/
@RestController
public class FristController {

   @RequestMapping(value = "/",method = RequestMethod.GET)
   public String HelloWorld(){
       return "HelloWorld";
   }

}
           

此時運作Bootdemo01Application,我們可以看到誰浏覽器列印出HelloWorld。第一個springboot應用就做好了,搭建确實簡便了很多。

幾個問題:

1、我們看到controller類的注解為@RestController,那麼@RestController和@Controller有什麼差別呢?

@RestController注解相當于@ResponseBody + @Controller合在一起的作用。

如果隻是使用@RestController注解Controller,則Controller中的方法無法傳回jsp頁面,配置的視圖解析器InternalResourceViewResolver不起作用,傳回的内容就是Return 裡的内容。

如果需要傳回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。

如果需要傳回JSON,XML或自定義mediaType内容到頁面,則需要在對應的方法上加上@ResponseBody注解。

現在都講前後端分離,傳輸的都是json,很少用jsp頁面了,那@RestController可能用的更多一些。

2、如果8080端口被占用了,我們希望使用别的端口通路怎麼辦?

工程下resources/application.properties裡面加上:server.port=8081即可

3、如何讀取配置檔案中的資訊?

在resources下有一個預設的配置檔案application.properties,我們在項目中不使用properties配置檔案,而是使用更加友善簡潔的yml檔案。項目結構:

springboot學習-搭建第一個springboot應用

我們舉執行個體來了解一下讀取配置檔案資料的方法:

首先,在yml中配置一個使用者資訊,包含使用者名及密碼:

server:
  port: 8080
username: xiaozhi
password: 12345

在Controller中使用@Value注解讀取該配置資訊:
package com.javazhiyin;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by 57783 on 2018/7/4.
*/
@RestController
public class FristController{

    @Value("${username}")
    private String username;

    @Value("${password}")
    private String password;

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String HelloWorld(){
        return "使用者名:"+username+";"+"密碼:"+password;
    }

}
           

此時,通路localhost:8080,出現如下頁面:

springboot學習-搭建第一個springboot應用

就可以看到springboot讀取配置檔案成功了。

原文釋出時間為:2018-07-11

本文作者:後端君

本文來自雲栖社群合作夥伴“

Java知音

”,了解相關資訊可以關注“