【java】1000問3SpringBoot空項目如何創建最簡易API

1、首先確認搭建的demo沒有報錯,當前我使用的是jar方式。

在package中創建controller包,並創建HelloController

package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
 	@RequestMapping("/index")
 	public String index(String id){
 		return id;
 	}
}

之後直接運行DemoApplication:

瀏覽器訪問:http://localhost:8080/hello/index?id=123123 說明運行成功

如何更換端口號,比如說我配置了https,端口號爲43,那麼在配置文件application.properties 中進行配置:

在resources中加入application.properties文件,裏面加入 最好不要用空格。

server.port=8081

 

一般來說springBoot不使用properties來進行配置,而是使用.yml格式的文件來配置屬性文件如下:後期建議採集這種方式。注意內容修改完畢之後,將文件後綴改爲.yml

server:
  port: 8081

 

之後啓動項目報錯:

Caused by: org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character '\t(TAB)' that cannot start any token. (Do not use \t(TAB) for indentation)
 in 'reader', line 2, column 1:
    	port:8081
    ^
 	at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:419)

解決方式:刪除port前的tab改爲兩個個空格的縮進方式。

 

重新啓動項目報錯:

***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class

此時改爲yml默認是去加載一些數據庫配置信息的,但是沒有找到,所以報錯,在啓動類上添加註解:

package com.example.demo;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class DemoApplication {

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

}

重新啓動項目:(後面如果配置了yml的數據庫信息的話,就可以將這個註解刪除掉了。見第四問的配置)

啓動成功:

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