1. 程式人生 > >從零開始-使用IDEA建立SpringBoot專案

從零開始-使用IDEA建立SpringBoot專案

*注:此文章謹以記錄學習過程,分享學習心得!

剛剛開始瞭解SpringBoot框架,覺得很好用,覺得很有必要深入學習一下該框架,現在就來建立一個SpringBoot專案:
1、在IDEA上新建一個Project,選擇Spring Initializr,
Project SDK 選擇安裝的JDK;
Choose Initializr Service URL 選擇預設(Default:https://start.spring.io

選擇專案模板

點選Next

2、進行專案配置
設定專案陣列(group),專案標識(Artifact),Type選擇一個Maven Project 表示是一個maven專案
Version:專案版本號
Name:專案名稱
Description:專案描述
Package:專案包名

專案配置

點選Next 下一步

3、選擇專案模板
我們來選擇建立一個Web專案
選擇Spring Boot版本

選擇專案模板

4、設定專案名稱和專案路徑
設定專案名稱和專案路徑
設定完專案路徑,和專案名稱後,點選FInish,建立專案完成,需要進行專案構建,等一小會即可完成。

5、建立完成,我們刪除.mvn資料夾,mvnw檔案和 mvnw.cmd檔案
刪除檔案

6、我們來看一下maven配置的pom.xml檔案,裡面包含了SpringBoot專案執行所需的版本庫

pom.xml

SpringBoot執行所需庫為:

<!-- SpringBoot專案的基礎庫檔案-->
    <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
<!-- SpringBoot專案的基礎庫檔案-->
    <dependencies>
<!-- web專案庫-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
<!-- 測試所需庫-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

7、建立一個HelloService

package com.example.springbootdemo.service;

import org.springframework.stereotype.Service;

@Service
public interface HelloService {
    String sayHello();
}

8、建立HelloService的實現類HelloServiceImpl,實現sayHello()方法,返回"Hello World!"

package com.example.springbootdemo.service.impl;

import com.example.springbootdemo.service.HelloService;
import org.springframework.stereotype.Component;

@Component
public class HelloServiceImpl implements HelloService {
  @Override
  public String sayHello() {
      return "Hello World!";
  }
}


9、建立HelloController,呼叫HelloService實現類,列印"Hello World!"到瀏覽器

package com.example.springbootdemo.controller;

import com.example.springbootdemo.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class HelloController {
    @Autowired
    private HelloService helloService;

    @RequestMapping("/hello")
    @ResponseBody
    public String helloWorld(){
        return helloService.sayHello();
    }
}

10、見證奇蹟的時刻,我們來執行一下所建專案,看能不能跟我們預期一樣,在瀏覽器輸入訪問地址http://localhost:8080/hello
就可以看到Hello World!
至此,學習建立一個SpringBoot專案就完成了。
檢視原始碼