springboot之取消starter的自動注入

springboot之取消starter的自動注入

starer是spring boot中一個很重要的概念,starter相當於一個模塊,它能將所需要的的依賴整合在一起並對模塊內的bean自動裝配到spring IOC容器,使用者只需要在maven中依賴相應的starter包並無需做過多的依賴即可進行開發。

一、例子

比如,我們導入了mybatis相關的依賴,但是我可能暫時沒用到數據庫,所以就沒有做數據庫相關的配置,這時候項目就會無法啓動

2020-03-08 22:13:10.396  WARN 10692 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: 

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource 

[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; 

nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate 
[com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception;

 nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class

因爲springboot中默認的數據庫連接池是hikari,你沒有在application.properties裏面進行數據庫相關的配置的話,那麼就會無法自動裝載dataSource

Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]

那麼重點來了,如何取消相關starer的自動注入?

我們還是以數據庫的這個爲例子:

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

那麼,就需要在啓動類加上如上配置,取消DataSourceAutoConfiguration的自動注入

 

springbootApplication是一個組合註解,其實裏面真正實現自動注入功能的,是這個EnableAutoConfiguration註解 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章