Spring Boot入門 ---- Hello World

-> 從Hello World 開始

   1、新建一個Maven項目

如何在idea新建maven項目

 

2、在pom.xml導入依賴

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <dependencies>
        <!--Spring boot的核心包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--Spring boot整合web開發的jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

3、 編寫一個HelloController

 附上代碼:

package cn.ok;

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

@SpringBootApplication
@Controller
public class HelloController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "Hello! Boot!!";
    }

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

4、啓動(main方法)

這樣,一個SpringBoot的項目就啓動起來了;

這時,可以在控制檯上看到 8080 的端口信息(因爲springboot內置了tomcat)。

5、訪問 http://localhost:8080/hello 

完成......SpringBoot就是這麼方便快捷!!!


 -> 對上面Demo的一些小結:

1:對於SpringBoot項目應該打什麼包?
     無論是普通應用還是web應用,都打jar包就可以了。
 
2:而爲什麼要在pom.xml中使用父項目spring-boot-starter-parent呢? 
      因爲它幫我們管理和導入了許多的基礎依賴。
 
3:爲什麼項目直接啓動起來就能在瀏覽器訪問?
      因爲引入了 spring-boot-starter-web ,它集成了運行網站應用的相關環境和工具(SpringMVC / Tomcat / Jackson 等等);
      依賴中嵌入的Tomcat9服務器,默認端口8080
 
4: 爲什麼要@SpringBootApplication註解?
        它內部是3大註解功能的集成:
       (1)@ComponentScan: 開啓組件掃描   ;
       (2)@SpringBootConfifiguration: 作用等同於@Confifiguration註解,也是用於標記配置類;
       (3)@EnableAutoConfifiguration: 內部導入AutoConfifigurationImportSelector。 
  

5:SpringApplication.run(..)的有什麼作用?
         (1)啓動SpringBoot應用
         (2)加載自定義的配置類,完成自動配置功能
       (3)把當前項目配置到嵌入的Tomcat服務器
       (4)啓動嵌入的Tomcat服務器
     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章