问题描述:
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);
}
}