springboot深入學習(一)-----springboot核心、配置檔案載入、日誌配置
一、@SpringBootApplication
@SpringBootApplication是spring boot的核心註解,原始碼如下:
相當於:@[email protected][email protected]
@Configuration:此類是一個配置
@EnableAutoConfiguration:讓springboot根據類路徑中的jar包依賴為當前專案進行自動配置
@ComponentScan:springboot自動掃描入口類所在包以及其子包裡的bean
另外springboot也可以關閉特定的自動配置:@SpringBootApplication(exlude = {DataSourceAutoConfiguration.class})
二、SpringBoot配置檔案
1、application.properties或application.yml
SpringBoot的全域性配置檔案為applicaiton.properties或者application.yml,通常放在src/main/resources/下,如下:
同樣也可以使用yml編寫,示例如下(將tomcat預設埠修改為8001、將預設訪問路徑修改為/index):
A、application.properties
server.port=8001
server.context-path=/index
B、application.yml
server:
port:8001
context-path: /index
2、載入xml
springboot提倡零配置,但是專案中難免需要使用xml配置,引入方式如下:
@ImportResource({"classpath:some-context.xml", "classpath:another-context.xml"})
三、外部配置
1、常規屬性配置
在spring的專案中,通過@PropertySource指明properties檔案的位置,然後可以通過@Value注入值。在SpringBoot裡,只需要在appllication.properties檔案中定義屬性,直接使用@Value即可
示例:
application.properties檔案增加屬性:
執行結果:
注意點:
A、@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) ----------------------->專案啟動的時候會報錯,提示沒有資料來源,因此在初始化bean的時候,排除這個bean
B、專案執行地址是不需要專案名的,直接使用http://localhost:8080/index,而不是http://localhost:8080/專案名稱/index
2、型別安全的配置
通過@Value的方式配置屬性也可以,但是當屬性過多時,會寫許多個@Value,同時也不美觀,因此springboot還提供了@ConfigurationProperties將屬性與一個bean關聯,示例如下:
執行結果:
注意點:
A、使用lombok的@Data可以省去寫get、set方法
B、有時候會提示一個錯誤:Spring Boot Annotion processor not found in classpath
這時需要新增一個依賴,如下:
C、在載入application.properties中的屬性時,不需要指定location,如果是在其他自定義的properties檔案中去載入屬性,則需要加上location
@ConfigurationProperties(prefix = "xxx", locations = {"classpath:/xxx.properties"})
四、日誌配置
springboot支援log4j、logback等等作為日誌框架,但是預設日誌框架使用的是logback,示例如下:
配置日誌檔案:
logging.file=D:/mylog/log.log
配置日誌級別:
logging.level.org.springframework.web=DEBUG