SpringBoot入門

“學而不思則罔,思而不學則殆”
本文主要用來參照SpringBoot學習視頻,記錄新手SpringBoot的學習筆記

SpringBoot簡介

  • SpringBoot簡化Spring開發的一個框架
  • 整個Spring技術棧的一個大集合(包含各種starter)
  • J2EE一站式開發解決方案

微服務

相關聯的時代背景:微服務
微服務是一種架構風格,相比於之前的ALL IN ONE的風格;微服務每一個應用都是一組小型服務,可以通過HTTP的方式進行通信;同時每個功能元素最終都可以進行獨立的升級和替換

HelloWorld項目構建

  1. 建立Maven項目
    先不使用Initializer,只是使用IDEA建立一個Maven項目
  2. 引入starter
    maven工程最重要的是配置pom.xml,對於SpringBoot項目,必須要配置starter的parent
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
 </parent>

對於一般的web項目,同時需要引入spring-boot-starter-web依賴,該依賴內嵌tomcat,後面項目可以不用生成war放置在tomcat容器中;只需要生成可執行jar包即可運行

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 創建主程序
    主程序使用@SpringBootApplication註解
@SpringBootApplication
public class HelloWorldMainApplication {
    public static void main(String[] args) {
        //Spring應用啓動起來
        SpringApplication.run(HelloWorldMainApplication.class, args);
    }
}
  1. 創建Controller和Service
@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello Springboot";
    }
}
  1. 啓動運行
    創建完成後便可以啓動運行,訪問http://localhost:8080/hello便可以

  2. 便捷部署(生成可執行jar包,其中內嵌tomcat可以直接運行)
    在POM文件中對增加build插件

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build> 

HelloWorld項目探究

  1. 父項目spring-boot-starter-parent
    其中spring-boot-starter-parent的父項目爲spring-boot-dependencies,它來真正管理SpringBoot應用裏面所有的版本依賴關係(使用Spring框架會遇見各種版本不匹配的問題);以後在項目中導入依賴默認是不需要寫版本號的(除非在dependencies中沒有相關的聲明版本號)

  2. 啓動器starter
    spring-boot-starter-web;SpringBoot將所有的場景都抽取出來,做成一個個的starter,只需要引用相關的starter,相關的場景所有的依賴都會導入進來。

  3. 主程序類、主入口類
    使用@SpringBootApplication作爲程序的主入口,相關詳細的註解如下

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication 

其中重點的註解爲 @EnableAutoConfiguration,該註解會將主配置(@SpringBootApplication標註的類)的所有包及一下所有的子包內的所有組件掃描到Spring容器中
@Import({AutoConfigurationImportSelector.class})
實際就是給容器導入這個場景所需要的所有組將,並配置好這些組件。

使用Spring Initializer快速建立工程

使用IDEA或者spring官網上,可以直接勾選相應的starter,構建相應的工程。
其中resource文件夾的目錄結構:

  • static:保存所有的靜態資源:js css images
  • template:保存所有的模板頁面(Spring
    Boot默認jar包使用嵌入式的Tomcat,默認不支持JSP頁面),可以使用模板引擎(freemarker、thymeleaf)
  • application.properties:Spring Boot應用配置文件,可以更改一些默認配置文件。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章