SpringBoot第一個工程創建(開發工具Idea)

使用Idea來構建我們第一個Springboot工程

Idea版本:IntelliJ IDEA 2019.2.4 (Community Edition)

這裏我們有兩種創建Spring Boot項目的方法。

一、在線創建項目
訪問Spring Boot的官方網站,在線創建項目然後本地導入我們的IDEA中就可以了。
1、訪問網址:https://start.spring.io/
根據提示配置項目信息,配置好之後點擊Generate Project按鈕生成項目。

2、將下載的項目解壓後導入到IDEA中即可。
點擊IDEA File --> New --> Project from Existing Sources… => 選擇你解壓後的項目文件夾目錄 --> 點擊Ok --> 選擇Import project from external model --> 選中Maven --> 一路點擊Next直到項目導入成功。

二、在Idea工具中創建項目(推薦)
利用IDEA工具裏面的Spring Assistant創建並初始化一個項目(推薦這種方式來創建項目)
1、File --> New --> Project… ,選擇Spring Assistant。
在這裏插入圖片描述
========遇到沒有Spring Assistant問題?
File --> Settings… --> Plugins 可以找到,安裝這個插件,重啓idea就可以
實測OK
《截圖說明下》
========問題已解決

2、根據工具提示一步步創建工程。
在這裏插入圖片描述

3、maven更新依賴

這個時候還沒有配置maven,可能會遇到自動更新出問題的情況。
在這裏插入圖片描述
如果這個目下沒有這個文件,就使用everything搜索一下,copy一個過來配置。配置完成重啓下idea就可以正常更新依賴文件了。

我這邊遇到一個“Cannot resolve plugin org.springframework.boot:spring-boot-maven-plugin:2.2.6.RELEASE”問題。
這個是由於在默認的maven倉庫找不到這個依賴,我們添加aliyun的maven庫。
========如何添加aliyun的maven倉庫?
參考地址:https://www.cnblogs.com/belibai/p/11370720.html

先找到我們工程使用的Maven(有可能配置了多個Maven)
進入Settings --> Maven ,選擇默認的Bundled (Maven 3)。這個時候就需要找到你的Manen settings.xml文件的路徑了(工具上有提示)。

找到mirrors,添加以下內容

<mirror>  
      <id>alimaven</id>  
      <name>aliyun maven</name>  
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
      <mirrorOf>central</mirrorOf>          
</mirror>

這裏是引用

注意這個是配置本地的倉庫的。(下載下來的依賴文件就會放在這個目錄下)
D:/MavenRepository/repo

修改完成了配置,idea提示修改,確認後,再右擊工程 --> Maven --> Reimport 就可以了。
========問題已解決

實測OK,沒有報錯了。

三、創建一個最簡單的Controller,瀏覽器中訪問測試
在包名下創建一個目錄 controller,再創建一個HelloController.java

package com.example.demo.controller;

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

@Controller
public class HelloController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String hello(){
        return "hello springboot";
    }
}
注意:
1、我們瀏覽器中的url使用的是value = "/hello" ,方法名稱不要求和這個一樣,但爲了規範還是一樣比較好。
2、@ResponseBody這個必須加上

========遇到一個啓動失敗的問題
報錯信息如下:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
//無法配置數據庫,沒有指定url屬性,並且無法配置embedded datasource
Reason: Failed to determine a suitable driver class
//原因:無法明確指定正確的驅動類(driver.class)
 
Action:
 
Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

解決方法:

程序入口處:
 
@SpringBootApplication
public class DemoApplication {
 
修改爲:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class DemoApplication {
}

在這裏插入圖片描述

========問題已解決

瀏覽輸入:http://localhost:8080/hello 頁面就會正常返回我們這個 hello springboot 了。

在這裏插入圖片描述

總結:使用Springboot我們都不用部署tomcat,很方便。

四、添加swagger
swagger就是一款讓你更好的書寫API文檔的框架,而且swagger可以完全模擬http請求,入參出參和實際情況差別幾乎爲零。
添加的步驟:
1、配置pom.xml
在dependencys標籤中添加

	<dependency>
		<groupId>io.springfox</groupId>
		<artifactId>springfox-swagger2</artifactId>
		<version>2.5.0</version>
	</dependency>
	<!-- swagger-ui -->
	<dependency>
		<groupId>io.springfox</groupId>
		<artifactId>springfox-swagger-ui</artifactId>
		<version>2.5.0</version>
	</dependency>

同步下就可以下載對應的依賴了。

2、配置config
在代碼中新建一個config包,然後再創建SwaggerConfig類

	package com.example.demo.config;

	import org.springframework.context.annotation.Bean;
	import org.springframework.context.annotation.Configuration;

	import io.swagger.annotations.ApiOperation;
	import springfox.documentation.builders.ApiInfoBuilder;
	import springfox.documentation.builders.RequestHandlerSelectors;
	import springfox.documentation.service.ApiInfo;
	import springfox.documentation.spi.DocumentationType;
	import springfox.documentation.spring.web.plugins.Docket;
	import springfox.documentation.swagger2.annotations.EnableSwagger2;

	@Configuration
	@EnableSwagger2
	public class SwaggerConfig {

		@Bean
		public Docket swaggerSpringMvcPlugin() {
			return new Docket(DocumentationType.SWAGGER_2)
					.apiInfo(apiInfo())//在swagger頁面顯示的title
					.select()
					.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
					.build();
		}

		/**
		 * 在swagger頁面顯示的title
		 * @return
		 */
		private ApiInfo apiInfo() {
			return new ApiInfoBuilder()
					.title("Demo 接口Api")
					.version("1.0")
					.build();
		}

	}

3、配置controller

	package com.example.demo.controller;

	import io.swagger.annotations.Api;
	import io.swagger.annotations.ApiOperation;
	import org.springframework.stereotype.Controller;
	import org.springframework.web.bind.annotation.RequestMapping;
	import org.springframework.web.bind.annotation.RequestMethod;
	import org.springframework.web.bind.annotation.ResponseBody;

	@Api(value = "測試Demo接口")//swagger配置
	@Controller
	public class HelloController {
		@ApiOperation(notes = "輸出hello springboot文本", value = "測試接口", httpMethod = "GET")//swagger配置
		@RequestMapping(value = "/hello", method = RequestMethod.GET )//produces = "application/json"輸出的json字符串
		@ResponseBody
		public String hello(){
			System.out.println("hello springboot");
			return "hello springboot";
		}
	}
主要就配置1個地方:@ApiOperation

4、測試:
瀏覽器打開:http://localhost:8080/swagger-ui.html
《截圖說明》

實際測試OK

========遇到個問題:
在idea中運行會報代碼錯誤。但是使用mvn clean package 打包運行是正常的。(說明代碼沒問題)

Error:(4, 30) java: 程序包io.swagger.annotations不存在

經過仔細排查,可能問題在於之前的maven的settings.xml的配置哪裏不對。如果通過everything搜索下這個jar依賴,我們指定的D:/MavenRepository/repo倉庫中有,而這個默認的C:\Users…m2\repository中沒有。

再看我們Idea的maven配置,發現並沒有勾選overwrite。
在這裏插入圖片描述
這個localRepository本地倉庫指定並沒有生效。還是找到默認的Bunde(Maven3)裏面的配置文件(這個裏面是沒有配置localRepository的)指向的是C:\Users…m2\repository這個倉庫。而這個倉庫剛好就沒有這個包。所以報錯了。

解決方法:
刪除C:\Users…m2\settings.xml配置文件,從網上下載個maven(下載網址http://maven.apache.org/download.cgi)
在這裏插入圖片描述

配置個環境變量(mvn --version)看看是否生效
在這裏插入圖片描述
在這裏插入圖片描述
========問題解決

========遇到一個啓動swagger時,瀏覽器彈框報錯問題

Unable to infer base url.
This is common when using dynamic servlet registration or when the API is behind an API Gateway.
The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/.
Please enter the location manually:

替換版本解決(從2.5.0替換爲2.9.2)

		<!--添加swagger-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<!-- swagger-ui -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

========問題解決

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