springboot 學習筆記(一)


(一)搭建一個簡單的springboot項目

  一、環境依賴

    (1)最低需要jdk8,不建議使用jdk10及以上版本,可能會報錯。

    (2)需要gradle4.0或maven3.2以上版本,本文使用maven進行管理。

    (3)集成開發工具,eclipse或者是idea,idea需要付費使用,本文使用eclipse開發。

  二、手工搭建一個springboot項目,輸出一個helloworld

    jdk安裝、環境變量配置,maven安裝調試在這里就不說明了

    (一)創建一個maven工程

    1、打開eclispse,new-》file-》other project 出現下圖,找到Maven項目,選在maven project

    

    2、勾選create a simple project 

3、填寫好group id 、artifact id,點擊finish  就創建好一個簡單的maven工程。

    (二)添加springboot依賴

    (1)新建項目的pom.xml文件中復制下列內容,這里我使用的springboot 2.1.0版本

<?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.zc</groupId>
    <artifactId>springboot_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  <!-- springboot的父級依賴,用以提供maven的相關依賴,這里選擇2.1.0版本 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath />
    </parent>
  <!-- 配置運行環境 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
  <!-- 引入springboot的web依賴 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>
    

    (2)依賴包下載完成后,項目可能會報錯,這時只要右鍵項目,maven-》update project

(3)我們寫一個簡單的controller,輸出一個helloworld,這里在controller中運行了一個main方法,使用@EnableAutoConfiguration為springboot提供給一個程序入口,正常情況下我們應該單獨寫一個入口類,這時要確保這個類在項目代碼的根目錄,以確保項目運行時能夠掃描到所有的包。

/**
 * 
 */
package controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zc
 *
 */
@Controller
@EnableAutoConfiguration
public class TestController {
	
	@RequestMapping(value="/hello")
	@ResponseBody
	public String helloWorld() {
		
		return "hello world";
		
	}
	
	public static void main(String args[]) {
		SpringApplication.run(TestController.class, args);
	}

}

  (4)springboot繼承了tomcat,這是我們run java application,就可以通過localhost:8080/hello來輸出一個hello world 頁面了。

    springboot在注解的集成上做的很好。比如上面的程序中我們使用了 @ResponseBody 來向頁面輸出數據 ,其實springboot中有 @RestController 注解,集合了@Controller 和@ResponseBody,只需要在類上注解為 @RestController 就可以了。

 

 

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM