springboot启动常见的错误
一、引入druid后出现错误
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
方式一
启动类上添加排除注解
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
方式二
删除pom文件的数据库依赖
方式三
配置文件添加数据库的配置
二、无法注入DataSource
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean of type 'javax.sql.DataSource' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'dataSource' in 'JndiDataSourceAutoConfiguration' not loaded because @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'
- Bean method 'dataSource' in 'XADataSourceAutoConfiguration' not loaded because @ConditionalOnClass did not find required class 'javax.transaction.TransactionManager'
Action:
Consider revisiting the entries above or defining a bean of type 'javax.sql.DataSource' in your configuration.
方式一
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
三、引入feign后启动报错
2022-01-18 16:07:02.922 INFO 4012 --- [ main] com.zhcf.carloan.auth.AuthApplication : The following profiles are active: dev
2022-01-18 16:07:03.326 ERROR 4012 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Service id not legal hostname (BASIC_SERVER)
at org.springframework.util.Assert.state(Assert.java:76) ~[spring-core-5.2.8.RELEASE.jar:5.2.8.RELEASE]
产生的原因
Feign的服务名不能使用下划线,需使用短杠,即:“aa-bb”。
方式一
将服务名中的_改成-,或者让服务名中不包含_即可
方式二
将feign写成一个Service,然后使用Http协议去调用该服务,即可。
@Service
public class xxService {
@Autowired
private LoadBalancerClient loadBalancer;
//服务名称
private static final String SERVICE_NAME = "SERVICE_A";
@SuppressWarnings("unchecked")
public Resp<PropertyDetailDTO> queryDetailInfo(String orderId) {
ServiceInstance serviceInstance = loadBalancer.choose(SERVICE_NAME);
String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort()
+ "/api/app/order/queryDetailInfo";
Map<String, Object> map = new HashMap<String, Object>();
map.put("orderId", orderId);
try {
Map<String, Object> resultMap = OkHttpUtils.httpClientGetReturnAsMap(url, map, 6000);
return MapperUtils.mapToBean(resultMap, Resp.class);
} catch (Exception e) {
log.error("queryDetailInfo has error.", e);
return Resp.fail(ErrorCode.SYSTEM_ERROR);
}
}
···
}
四、oauth2.0 资源服务器启动报错
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.access.method.MethodSecurityMetadataSource]: Factory method 'methodSecurityMetadataSource' threw exception; nested exception is java.lang.IllegalStateException: In the composition of all global method configuration, no annotation support was actually activated
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
... 44 common frames omitted
Caused by: java.lang.IllegalStateException: In the composition of all global method configuration, no annotation support was actually activated
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityMetadataSource(GlobalMethodSecurityConfiguration.java:373) ~[spring-security-config-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_211]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_211]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
... 45 common frames omitted
产生的原因
@EnableGlobalMethodSecurity注解 prePostEnabled 属性,是否开启 PreAuthory 注解功能,类似的还有其他注解,Secured注解等等,这些注解的默认值都是false,也就是不启用
方式一
@EnableGlobalMethodSecurity(prePostEnabled = true)
五、启动Application出现命令太长
Error running YudaoServerApplication. Command line is too long.
Shorten the command line via JAR manifest or via a classpath file and rerun.
解决方式
方式一
- 首先找到项目里面的idea/workspace.xml文件,然后再找到 $\color{Red} {
} $标签
<component name="PropertiesComponent">
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/../../../zhcf/carloan/pre-loan" />
<property name="nodejs_package_manager_path" value="yarn" />
<property name="settings.editor.selected.configurable" value="MavenSettings" />
</component>
- 在这个标签中增加$\color{Red} {
} $标签
<component name="PropertiesComponent">
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/../../../zhcf/carloan/pre-loan" />
<property name="nodejs_package_manager_path" value="yarn" />
<property name="settings.editor.selected.configurable" value="MavenSettings" />
<property name="dynamic.classpath" value="true" />
</component>
方式二
- 1、打开Run/Debug Configurations窗体
- 2、按图标红的地方选择
六、gateway配合nacos路由报错:Unable to find instance for XXX
Spring Cloud的版本大于2020的版本 使用url能通过网关能正常路由
产生的原因
Spring Cloud2020移除了Ribbon
解决方案
增加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
七、swagger java.lang.NumberFormatException: For input string: ""
产生原因
使用了swagger注解,但对Long/Integer添加注解时未指定example值,如:
@ApiModelProperty(value = "主键id")
private Long id;
源码:AbstractSerializableParameter类中
@JsonProperty("x-example")
public Object getExample() {
if (example == null) {
return null;
}
try {
if (BaseIntegerProperty.TYPE.equals(type)) {
return Long.valueOf(example);
} else if (DecimalProperty.TYPE.equals(type)) {
return Double.valueOf(example);
} else if (BooleanProperty.TYPE.equals(type)) {
if ("true".equalsIgnoreCase(example) || "false".equalsIgnoreCase(defaultValue)) {
return Boolean.valueOf(example);
}
}
} catch (NumberFormatException e) {
LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", defaultValue, type), e);
}
return example;
}
解决方案
方式一
Long类型上的参数或属性上使用swagger注解时,指定example的值为数值型,比如:
@ApiModelProperty(value = "主键id",example="1")
private Long id;
方式二
升级swagger-models版本号大于1.5.20,如
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
八、mybatis-plus中使用动态数据源时出现以下的问题
1、分页插件不生效
2、org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
3、自动填充MetaObjectHandler失效
解决方案
配置SqlSessionFactory,覆盖默认的的SqlSessionFactory
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource());
sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper.xml"));
Interceptor[] plugins = new Interceptor[1];
plugins[0] = mybatisPlusInterceptor();
sqlSessionFactory.setPlugins(plugins);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
configuration.setCallSettersOnNulls(true);
sqlSessionFactory.setConfiguration(configuration);
//全局配置
GlobalConfig globalConfig = new GlobalConfig();
//配置填充器
globalConfig.setMetaObjectHandler(metaObjectHandler);
sqlSessionFactory.setGlobalConfig(globalConfig);
return sqlSessionFactory.getObject();
}
mybatisPlusInterceptor() 这个就是通常配置的mybatisPlusInterceptor的bean
九、bootstrap.yml文件无法加载
解决方案
项目添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
注意:本文归作者所有,未经作者允许,不得转载