javascript
SpringBoot基础篇
配置maven
file-setting-build-build tool
將項目配置成可執行jar
1打包
mavenProject-lifecircle-package
2尋找
target
3執行
cd 包在的目錄- java -jar
Spring Inititer
resource的目錄結構:static:靜態資源? ? templates:模板頁面? application.properties:應用全局配置文件
yaml
yml:yaml a(isn't) makeup language :一個標記語言
優勢:以數據為中心
書寫格式:
k: v:字面直接來寫;
字符串默認不用加上單引號或者雙引號;
"":雙引號;不會轉義字符串里面的特殊字符;特殊字符會作為本身想表示的意思
name: "zhangsan \n lisi":輸出;zhangsan 換行 lisi
'':單引號;會轉義特殊字符,特殊字符最終只是一個普通的字符串數據
name: ‘zhangsan \n lisi’:輸出;zhangsan \n lisi
對象還是k: v的方式
friends:
lastName: zhangsan
age: 20
friends
用- 值表示數組中的一個元素
pets行內寫法
pets
person:
lastName: hello
age: 18
boss: false
birth: 2017/12/12
maps: {k1: v1,k2: 12}
lists:
- lisi
- zhaoliu
dog:
name: 小狗
age: 12
javaBean:?將配置文件中配置的每一個屬性的值,映射到這個組件中
@Component//只有這個組件是容器中的組件,才能容器提供的@ConfigurationProperties功能;
@ConfigurationProperties(prefix = "person")//告訴SpringBoot將本類中的所有屬性和配置文件中相關的配置進行綁定;
* prefix = "person":配置文件中哪個下面的所有屬性進行一一映射
@Validated//
public class Person {
//lastName必須是郵箱格式
@Email
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
<!--導入配置文件處理器,配置文件進行綁定就會有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
?@PropertySource(value = {"classpath:person.properties"})
默認使用application.properties的配置;
server:
port: 8081
spring:
profiles:
active: prod
---
server:
port: 8083
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: prod #指定屬于哪個環境
在配置文件中指定 spring.profiles.active=dev
–file:./config/
–file:./
–classpath:/config/
–classpath:/
優先級由高到底,高優先級的配置會覆蓋低優先級的配置;
SpringBoot會從這四個位置全部加載主配置文件
Spring Boot里面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;
想讓Spring的配置文件生效,加載進來;
@ImportResource標注在一個配置類上
不來編寫Spring的配置文件
SpringBoot推薦給容器中添加組件的方式;推薦使用全注解的方式
1、配置類@Configuration------>Spring配置文件
2、使用@Bean給容器中添加組件
/*** @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件
*
* 在配置文件中用<bean><bean/>標簽添加組件
*
*/
自動配置的原理
1)、SpringBoot啟動的時候加載主配置類,開啟了自動配置功能 ==@EnableAutoConfiguration==
2)、@EnableAutoConfiguration 作用:
-
利用EnableAutoConfigurationImportSelector給容器中導入一些組件?
-
可以查看selectImports()方法的內容;
-
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);獲取候選的配置
- SpringFactoriesLoader.loadFactoryNames()
掃描所有jar包類路徑下 ?META-INF/spring.factories
把掃描到的這些文件的內容包裝成properties對象
從properties中獲取到EnableAutoConfiguration.class類(類名)對應的值,然后把他們添加在容器中
- SpringFactoriesLoader.loadFactoryNames()
==將 類路徑下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中;==
# Auto Configureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
........
每一個這樣的 xxxAutoConfiguration類都是容器中的一個組件,都加入到容器中;用他們來做自動配置;
3)、每一個自動配置類進行自動配置功能;
4)、以HttpEncodingAutoConfiguration(Http編碼自動配置)為例解釋自動配置原理;
根據當前不同的條件判斷,決定這個配置類是否生效?
一但這個配置類生效;這個配置類就會給容器中添加各種組件;這些組件的屬性是從對應的properties類中獲取的,這些類里面的每一個屬性又是和配置文件綁定的;
5)、所有在配置文件中能配置的屬性都是在xxxxProperties類中封裝者;配置文件能配置什么就可以參照某個功能對應的這個屬性類
精髓:
? 1)、SpringBoot啟動會加載大量的自動配置類
? 2)、我們看我們需要的功能有沒有SpringBoot默認寫好的自動配置類;
? 3)、我們再來看這個自動配置類中到底配置了哪些組件;(只要我們要用的組件有,我們就不需要再來配置了)
? 4)、給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。我們就可以在配置文件中指定這些屬性的值。
?
xxxxAutoConfigurartion:自動配置類;
給容器中添加組件
xxxxProperties:封裝配置文件中相關屬性;
?
2、細節
?
1、@Conditional派生注解(Spring注解版原生的@Conditional作用)
作用:必須是@Conditional指定的條件成立,才給容器中添加組件,配置配里面的所有內容才生效;
| @ConditionalOnJava | 系統的java版本是否符合要求 |
| @ConditionalOnBean | 容器中存在指定Bean; |
| @ConditionalOnMissingBean | 容器中不存在指定Bean; |
| @ConditionalOnExpression | 滿足SpEL表達式指定 |
| @ConditionalOnClass | 系統中有指定的類 |
| @ConditionalOnMissingClass | 系統中沒有指定的類 |
| @ConditionalOnSingleCandidate | 容器中只有一個指定的Bean,或者這個Bean是首選Bean |
| @ConditionalOnProperty | 系統中指定的屬性是否有指定的值 |
| @ConditionalOnResource | 類路徑下是否存在指定資源文件 |
| @ConditionalOnWebApplication | 當前是web環境 |
| @ConditionalOnNotWebApplication | 當前不是web環境 |
| @ConditionalOnJndi | JNDI存在指定項 |
自動配置類必須在一定的條件下才能生效;
我們怎么知道哪些自動配置類生效;
==我們可以通過啟用 debug=true屬性;來讓控制臺打印自動配置報告==,這樣我們就可以很方便的知道哪些自動配置類生效;
日志
? 寫了一個統一的接口層;日志門面(日志的一個抽象層);logging-abstract.jar;
? 給項目中導入具體的日志實現就行了;我們之前的日志框架都是實現的抽象層;
?
市面上的日志框架;
JUL、JCL、Jboss-logging、logback、log4j、log4j2、slf4j....
| JCL(Jakarta Commons Logging) SLF4j(Simple Logging Facade for Java) jboss-logging | Log4j JUL(java.util.logging) Log4j2 Logback |
左邊選一個門面(抽象層)、右邊來選一個實現;
日志門面: SLF4J;
日志實現:Logback;?
SpringBoot:底層是Spring框架,Spring框架默認是用JCL;‘
? ==SpringBoot選用 SLF4j和logback;==
2、SLF4j使用
1、如何在系統中使用SLF4j https://www.slf4j.org
以后開發的時候,日志記錄方法的調用,不應該來直接調用日志的實現類,而是調用日志抽象層里面的方法;
給系統里面導入slf4j的jar和 logback的實現jar
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
public class HelloWorld {
?public static void main(String[] args) {
? ?Logger logger = LoggerFactory.getLogger(HelloWorld.class);
? ?logger.info("Hello World");
}
}
圖示;
每一個日志的實現框架都有自己的配置文件。使用slf4j以后,配置文件還是做成日志實現框架自己本身的配置文件;
2、遺留問題
a(slf4j+logback): Spring(commons-logging)、Hibernate(jboss-logging)、MyBatis、xxxx
統一日志記錄,即使是別的框架和我一起統一使用slf4j進行輸出?
如何讓系統中所有的日志都統一到slf4j;
==1、將系統中其他日志框架先排除出去;==
==2、用中間包來替換原有的日志框架;==
==3、我們導入slf4j其他的實現==
?
3、SpringBoot日志關系
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
?
SpringBoot使用它來做日志功能;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
底層依賴關系
總結:
? 1)、SpringBoot底層也是使用slf4j+logback的方式進行日志記錄
? 2)、SpringBoot也把其他的日志都替換成了slf4j;
? 3)、中間替換包?
? 4)、如果我們要引入其他框架?一定要把這個框架的默認日志依賴移除掉?
? Spring框架用的是commons-logging;
<dependency><groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
==SpringBoot能自動適配所有的日志,而且底層使用slf4j+logback的方式記錄日志,引入其他框架的時候,只需要把這個框架依賴的日志框架排除掉即可;==
4、日志使用;
1、默認配置
SpringBoot默認幫我們配置好了日志;
//記錄器Logger logger = LoggerFactory.getLogger(getClass());
日志輸出格式:%d表示日期時間,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%logger{50} 表示logger名字最長50個字符,否則按照句點分割。 %msg:日志消息,%n是換行符-->%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
SpringBoot修改日志的默認配置
logging.level.com.atguigu=trace#logging.path=
# 不指定路徑在當前項目下生成springboot.log日志
# 可以指定完整的路徑;
#logging.file=G:/springboot.log
?
# 在當前磁盤的根路徑下創建spring文件夾和里面的log文件夾;使用?spring.log 作為默認文件
logging.path=/spring/log
?
# 在控制臺輸出的日志的格式
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# 指定文件中日志輸出的格式
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} ==== %msg%n
| (none) | (none) | ? | 只在控制臺輸出 |
| 指定文件名 | (none) | my.log | 輸出日志到my.log文件 |
| (none) | 指定目錄 | /var/log | 輸出到指定目錄的 spring.log 文件中 |
2、指定配置
給類路徑下放上每個日志框架自己的配置文件即可;SpringBoot就不使用他默認配置的了
| Logback | logback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy |
| Log4j2 | log4j2-spring.xml or log4j2.xml |
| JDK (Java Util Logging) | logging.properties |
logback.xml:直接就被日志框架識別了;
logback-spring.xml:日志框架就不直接加載日志的配置項,由SpringBoot解析日志配置,可以使用SpringBoot的高級Profile功能
<springProfile name="staging">? ?<!-- configuration to be enabled when the "staging" profile is active -->
可以指定某段配置只在某個環境下生效
</springProfile>
如:
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">? ? ? ?<!--
? ? ? ?日志輸出格式:
%d表示日期時間,
%thread表示線程名,
%-5level:級別從左顯示5個字符寬度
%logger{50} 表示logger名字最長50個字符,否則按照句點分割。
%msg:日志消息,
%n是換行符
? ? ? ?-->
? ? ? ?<layout class="ch.qos.logback.classic.PatternLayout">
? ? ? ? ? ?<springProfile name="dev">
? ? ? ? ? ? ? ?<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ---> %-5level %logger{50} - %msg%n</pattern>
? ? ? ? ? ?</springProfile>
? ? ? ? ? ?<springProfile name="!dev">
? ? ? ? ? ? ? ?<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ==== [%thread] ==== %-5level %logger{50} - %msg%n</pattern>
? ? ? ? ? ?</springProfile>
? ? ? ?</layout>
? ?</appender>
如果使用logback.xml作為日志配置文件,還要使用profile功能,會有以下錯誤
no applicable action for [springProfile]
5、切換日志框架
可以按照slf4j的日志適配圖,進行相關的切換;
slf4j+log4j的方式;
<dependency>
?<groupId>org.springframework.boot</groupId>
?<artifactId>spring-boot-starter-web</artifactId>
?<exclusions>
? ?<exclusion>
? ? ?<artifactId>logback-classic</artifactId>
? ? ?<groupId>ch.qos.logback</groupId>
? ?</exclusion>
? ?<exclusion>
? ? ?<artifactId>log4j-over-slf4j</artifactId>
? ? ?<groupId>org.slf4j</groupId>
? ?</exclusion>
?</exclusions>
</dependency>
?
<dependency>
?<groupId>org.slf4j</groupId>
?<artifactId>slf4j-log4j12</artifactId>
</dependency>
?
?
切換為log4j2
? <dependency>
? ? ? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ? ? ?<artifactId>spring-boot-starter-web</artifactId>
? ? ? ? ? ?<exclusions>
? ? ? ? ? ? ? ?<exclusion>
? ? ? ? ? ? ? ? ? ?<artifactId>spring-boot-starter-logging</artifactId>
? ? ? ? ? ? ? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ? ? ? ? ?</exclusion>
? ? ? ? ? ?</exclusions>
? ? ? ?</dependency>
?
<dependency>
?<groupId>org.springframework.boot</groupId>
?<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
?web配置開發
?
https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications
1. Spring MVC auto-configuration
Spring Boot 自動配置好了SpringMVC
以下是SpringBoot對SpringMVC的默認配置:==(WebMvcAutoConfiguration)==
-
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
-
自動配置了ViewResolver(視圖解析器:根據方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉發?重定向?))
-
ContentNegotiatingViewResolver:組合所有的視圖解析器的;
-
如何定制:我們可以自己給容器中添加一個視圖解析器;自動的將其組合進來;
-
-
Support for serving static resources, including support for WebJars (see below).靜態資源文件夾路徑,webjars
-
Static index.html support. 靜態首頁訪問
-
Custom Favicon support (see below). favicon.ico
?
-
自動注冊了 of Converter, GenericConverter, Formatter beans.
-
Converter:轉換器; public String hello(User user):類型轉換使用Converter
-
Formatter 格式化器; 2017.12.17===Date;
-
? ==自己添加的格式化器轉換器,我們只需要放在容器中即可==
-
Support for HttpMessageConverters (see below).
-
HttpMessageConverter:SpringMVC用來轉換Http請求和響應的;User---Json;
-
HttpMessageConverters 是從容器中確定;獲取所有的HttpMessageConverter;
==自己給容器中添加HttpMessageConverter,只需要將自己的組件注冊容器中(@Bean,@Component)==
?
-
-
Automatic registration of MessageCodesResolver (see below).定義錯誤代碼生成規則
-
Automatic use of a ConfigurableWebBindingInitializer bean (see below).
==我們可以配置一個ConfigurableWebBindingInitializer來替換默認的;(添加到容器)==
初始化WebDataBinder;
請求數據=====JavaBean;
org.springframework.boot.autoconfigure.web:web的所有自動場景;
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
2、擴展SpringMVC
? ?<mvc:view-controller path="/hello" view-name="success"/>? ?<mvc:interceptors>
? ? ? ?<mvc:interceptor>
? ? ? ? ? ?<mvc:mapping path="/hello"/>
? ? ? ? ? ?<bean></bean>
? ? ? ?</mvc:interceptor>
? ?</mvc:interceptors>
==編寫一個配置類(@Configuration),是WebMvcConfigurerAdapter類型;不能標注@EnableWebMvc==;
既保留了所有的自動配置,也能用我們擴展的配置;
//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能原理:
? 1)、WebMvcAutoConfiguration是SpringMVC的自動配置類
? 2)、在做其他自動配置時會導入;@Import(EnableWebMvcConfiguration.class)
? ?
? 3)、容器中所有的WebMvcConfigurer都會一起起作用;
? 4)、我們的配置類也會被調用;
? 效果:SpringMVC的自動配置和我們的擴展配置都會起作用;
3、全面接管SpringMVC;
SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己配置;所有的SpringMVC的自動配置都失效了
我們需要在配置類中添加@EnableWebMvc即可;
//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
原理:
為什么@EnableWebMvc自動配置就失效了;
1)@EnableWebMvc的核心
2)、
3)、
4)、@EnableWebMvc將WebMvcConfigurationSupport組件導入進來;
5)、導入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;
?
5、如何修改SpringBoot的默認配置
模式:
? 1)、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean、@Component)如果有就用用戶配置的,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來;
? 2)、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置
? 3)、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定制配置
?
轉載于:https://www.cnblogs.com/gdfs/p/10876874.html
總結
以上是生活随笔為你收集整理的SpringBoot基础篇的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Zxing 竖屏切换 android
- 下一篇: 基于kafka_2.11-2.1.0实现