springboot 如何取消starter的自動注入
springboot 取消starter的自動注入
starer是spring boot中一個很重要的概念,starter相當(dāng)于一個模塊,它能將所需要的的依賴整合在一起并對模塊內(nèi)的bean自動裝配到spring IOC容器,使用者只需要在maven中依賴相應(yīng)的starter包并無需做過多的依賴即可進行開發(fā)。
看例子
比如,我們導(dǎo)入了mybatis相關(guān)的依賴,但是我可能暫時沒用到數(shù)據(jù)庫,所以就沒有做數(shù)據(jù)庫相關(guān)的配置,這時候項目就會無法啟動
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中默認的數(shù)據(jù)庫連接池是hikari,你沒有在application.properties里面進行數(shù)據(jù)庫相關(guān)的配置的話,那么就會無法自動裝載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]
重點來了
如何取消相關(guān)starer的自動注入?
我們還是以數(shù)據(jù)庫的這個為例子:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
那么,就需要在啟動類加上如上配置,取消DataSourceAutoConfiguration的自動注入

springbootApplication是一個組合注解,其實里面真正實現(xiàn)自動注入功能的,是這個EnableAutoConfiguration注解
SpringBoot 自動注入問題
Description:
Field service in com.test.controller.UserController required a bean of type 'com.test.service.UserService' that could not be found.
Action:
Consider defining a bean of type 'com.test.service.UserService' in your configuration.
項目啟動的時候出現(xiàn)出現(xiàn)問題
run

controller

service

dao

配置文件如下

項目目錄

找了幾個類,該注解的也注解了。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot如何動態(tài)創(chuàng)建Bean示例代碼
這篇文章主要給大家介紹了關(guān)于Spring Boot如何動態(tài)創(chuàng)建Bean的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
IDEA使用jformdesigner插件做管理系統(tǒng)MVC架構(gòu)的步驟和實現(xiàn)思路
在?IntelliJ?IDEA?中結(jié)合?JFormDesigner?插件,通過?Swing?框架實現(xiàn)一個管理系統(tǒng)的?MVC?架構(gòu)是一種經(jīng)典的開發(fā)方式,以下是具體的步驟和實現(xiàn)思路,包含從項目創(chuàng)建到?MVC?架構(gòu)的核心代碼實現(xiàn),需要的朋友可以參考下2024-12-12
在Struts2中如何將父類屬性序列化為JSON格式的解決方法
本篇文章,小編將為大家介紹關(guān)于在Struts2中如何將父類屬性序列化為JSON格式的解決方法,有需要的朋友可以參考一下2013-04-04

