SpringBoot 02: 初識SpringBoot

1. SpringBoot產生原因

  • spring, springmvc框架使用上的一些缺點:
  • 需要使用的大量的配置文件
  • 還需要配置各種對象
  • 需要把使用的對象放入到spring容器中才能使用對象
  • 需要了解其他框架配置規則
  • springboot的一些直觀優點:
  • SpringBoot就相當于簡化了配置文件的Spring+SpringMVC(但springboot的核心還是IOC容器)
  • 常用的框架和第三方庫都已經配置好了, 只需要引入使用即可
特點
  • Create stand-alone Spring applications
可以創建spring應用
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
內嵌的tomcat, jetty, Undertow
  • Provide opinionated 'starter' dependencies to simplify your build configuration
提供了starter起步依賴, 簡化應用的配置:比如使用MyBatis框架, 需要在Spring項目中, 需要配置MyBatis的對象, SqlSessionFactory以及Dao的代理對象但在SpringBoot項目中, 只要在pom.xml里面加入一個mybatis-spring-boot-starter依賴
  • Automatically configure Spring and 3rd party libraries whenever possible
盡可能去自動配置spring和第三方庫, 叫做自動配置(就是把spring中的,第三方庫中的對象都創建好,放到容器中 , 開發人員可以直接使用)
  • Provide production-ready features such as metrics, health checks, and externalized configuration
提供了健康檢查, 統計, 外部化配置
  • Absolutely no code generation and no requirement for XML configuration
不用生成代碼,不需要使用xml文件做配置2. SpringBoot項目地址
  • 創建springboot項目時,可能用到的地址
  • 國外地址: https://start.spring.io
  • 國內地址: https://start.springboot.io
@SpringBootApplication注解
  • 位于項目啟動類上面 , 是復合注解, 包含以下注解
@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan
  • 而@SpringBootConfiguration又是包含@Configuration的符合注解
@Configurationpublic @interface SpringBootConfiguration {@AliasFor(annotation = Configuration.class)boolean proxyBeanMethods() default true;}//說明使用了@SpringBootConfiguration注解標注的類,可以作為配置文件使用的,可以使用Bean聲明對象 , 注入到容器
  • @EnableAutoConfiguration
啟用自動配置,把java對象配置好,注入到spring容器中 。例如可以把mybatis的對象創建好,放入到容器中
  • @ComponentScan
掃描器,找到注解,根據注解的功能創建對象,給屬性賦值等等 。默認掃描的包:@ComponentScan所在的類,以及其所在類所在的包和子包 。SpringBoot的配置文件
  • 名稱:application
  • 后綴:property(key=value) 或 yml(key:value)
  • 配置文件示例:
  • 例1:application.properties設置端口和上下文
#設置端口號server.port=9090#設置訪問應用上下文路徑,contextpathserver.servlet.context-path=/myboot
  • 例2:application.yml , 配置文件的結構更加清晰,推薦使用
server:port: 9090servlet:context-path:/myboot多環境配置文件
  • 實際場景中 , 項目的配置會有開發環境,測試環境 , 上線的環境
  • 每個環境有不同的配置信息,例如端口 , 上下文,數據庫url,用戶名,密碼等等
  • 使用多環境配置文件,可以方便的切換不同的配置
  • 使用方式:創建多個配置文件,名稱規則:application-環境名稱.properties(或者后綴未yml格式)
  • 多環境配置文件的示例如下:
  • 創建開發環境的配置文件:application-dev.properties(或者application-dev.yml )
  • 創建測試者使用的配置:application-test.properties
  • springboot默認讀取application.properties文件,故需在該文件中配置實際需要讀取的核心配置文件
#以激活配置文件 application-dev.properties為例spring.profiles.active=dev@ConfigurationProperties
  • 設計思想:把配置文件的數據映射到java對象的屬性上,將配置文件中某些開頭和prefix指定的值相同的對應配置文件中的值賦給對應屬性
  • 例如:application.properties
#自定義key=valueschool.name=橘子school.website=www.test.comschool.address=黑龍江哈爾濱