問題描述:
common 工程裏面定義對整個項目統一異常處理,而 web 工程需要 mian 啓動入口配置包掃描:
package com.tc.town.web;
@ComponentScan(basePackages = {"com.tc.town.common"})
@SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class,args);
}
}
來掃描 common工程中定義的統一異常處理類:
package com.tc.town.common.exception;
//控制器增強
@ControllerAdvice
public class ExceptionCatch {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);
//捕獲CustomException自定義異常
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseResult customException(CustomException customException){
customException.printStackTrace();
//記錄日誌
LOGGER.error("catch exception:{}",customException.getMessage());
ResultCode resultCode = customException.getResultCode();
return new ResponseResult(resultCode);
}
//捕獲Exception此類異常
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult exception(Exception exception){
exception.printStackTrace();
//記錄日誌
LOGGER.error("catch exception:{}",exception.getMessage());
//返回通用異常
return new ResponseResult(CommonCode.SERVER_ERROR);
}
}
這時,啓動 web 工程拋:
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.
Reason: Failed to determine a suitable driver class
錯誤原因:
根據錯誤提示,很明顯的告訴你。說我找不到驅動程序類,無法自動幫你配置數據源。
這是爲什麼呢?明明web工程定義了數據源配置,怎麼就找不到呢?
答案,在於 web 工程 mian 啓動方法上的這個註解:@ComponentScan(basePackages = {"com.tc.town.common"})
你仔細看我上面兩個工程的包結構:
web 工程: package com.tc.town.web;
common 工程:package com.tc.town.common;
發現原因沒有?
原因,就是我在web 工程 上面只配置了 掃描 common 工程包結構,那麼 web 工程就只會掃描 common 工程包路徑,而不會掃描本身 web 工程的路徑結構。這樣就導致了一啓動拋,找不到驅動程序類,無法自動配置數據源。
解決方案:
既然,是你找不到本身web 工程的包掃描,那麼我定義一個就好了。
@ComponentScan(basePackages = {"com.tc.town.common","com.tc.town.web"})
@SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class,args);
}
}