1 加载配置文件失败
- 问题
‘url’ attribute is not specified and no embedded datasource could be configured - 原因
springboot启动是为找到配置文件:application.yml - 解决
pom.xml文件中添加:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<build>
2 数据源加载失败
2.1 配置tomcat加载失败
- 问题
2019-12-30 13:21:43 [INFO] - {dataSource-1} closed - 原因
配置ssl证书时添加了type-alias: tomcat - 解决
删除key-alias: tomcat,启动文件配置tomcat
package com.sb;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SpringBootApplication
@MapperScan("com.sb.mapper")
@EnableSwagger2
@EnableCaching
public class SSLTest extends SpringBootServletInitializer{
private static Logger logger = LoggerFactory.getLogger(SSLTest.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(XStartVideoAnalysis.class);
}
@Bean
public TomcatServletWebServerFactory servletContainer(){
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(){
@Override
protected void postProcessContext(Context context){
// 强制使用https
// SecurityConstraint constraint = new SecurityConstraint();
// constraint.setUserConstraint("CONFIDENTIAL");
// SecurityCollection collection = new SecurityCollection();
// collection.addPattern("/*");
// constraint.addCollection(collection);
// context.addConstraint(constraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector(){
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
public static void main(String[] args){
SpringApplication.run(SSLTest.class, args);
logger.debug("测试日志级别DEBUG");
logger.warn("测试日志级别WARN");
logger.info("任务已启动");
}
}
2.2 开发环境没有证书
- 原因
开发环境没有证书,配置了Tomcat Bean - 方案
取消TomcatBean配置,将2.1中的@Bean注释即可。
3 内置Tomcat配置
配置文件:application.yml
server:
port: 8080
maxHttpHeaderSize: 8192
4 Springboot访问异常
- 异常信息
Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:428)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:684)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
- 原因
https端口使用http访问。 - 解决
https和http访问各自端口。
5 缓存
5.1 @CacheConfig
- 异常信息
No cache could be resolved for ‘Builder[public java.lang.String com.company.web.service.impl.GetTokenServiceImpl.getTokenFromCache()] caches=[] | key=’#token’ | keyGenerator=’’ | cacheManager=’’ | cacheResolver=’’ | condition=’’ | unless=’’ | sync=‘false’’ using resolver ‘org.springframework.cache.interceptor.SimpleCacheResolver@281d7903’. At least one cache should be provided per cache operation." - 原因
未配置@CacheConfig。 - 解决
配置@CacheConfig。
5.2 返回值缺少key
- 异常信息
Null key returned for cache operation (maybe you are using named params on classes without debug info?) Builder[public java.lang.String com.company.web.service.impl.GetTokenServiceImpl.getTokenFromCache()] caches=[token] | key=’#token’ | keyGenerator=’’ | cacheManager=’’ | cacheResolver=’’ | condition=’’ | unless=’’ | sync=‘false’ - 原因
执行函数没有使用key同名的参数 - 解决
执行函数使用与key同名的参数,如,key获取name,执行函数使用参数name。
@Cacheable(key = "#name")
@Override
public String getTokenFromCache(String name) {
Map returnMap = new HashMap();
GetToken getToken = new GetToken();
String token = getToken.tokenStr();
returnMap.put("token", token);
return token;
}
5.3 无法存储到Redis
- 异常
Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException: MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error. - 原因
Redis关闭写入权限。 - 解决
关闭redis-server,重启redis-server
ps aux | grep redis
kill -9 pid-num
# Mac环境添加配置文件
redis-server redis.conf
# Linux发行版
redis-server
6 数据转换失败
java.lang.String cannot be cast to com.alibaba.fastjson.JSONObject
7 POI获取数据行数
场景:Excel文档,共有5行数据,手动删除两行,还剩三行数据,POI工具获取Excel文件行数,是5行,不是3行。
原因:POI通过HSSFWorkbook类方法getSheetAt(row)获取文件sheet,进一步使用getLastRowNum()获取“有效”数据行数,共有两种情况:
1.获取未经过删减的Excel文件行数;
2.获取经过删减的Excel文件行数;
若获取经过删减的Excel文件行数,读取的行数为未删减之前的原始文件行数。
解决:
通过getRow(row)获取数据,判断该行数据是否为全空,若为全空,则结束读取,否则继续读取。
8 启动springboot失败
- 异常
2020-05-13 15:28:53 [INFO] - Stopping service [Tomcat]
2020-05-13 15:28:53 [INFO] -
Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.
- 原因
mapper文件内容(*.xml)格式有错误。 - 方案
检查mapper文件内容,本次异常因为namaspace与mapper文件文件名不对应。
9 时间解析失败
- 问题
JSON parse error: Cannot deserialize value of typejava.time.LocalDateTime
from String “2020-06-03”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2020-06-03’ could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-06-03 of type java.time.format.Parsed; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of typejava.time.LocalDateTime
from String “2020-06-03”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2020-06-03’ could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-06-03 of type java.time.format.Parsed\n at [Source: (PushbackInputStream); line: 3, column: 20] (through reference chain: com.company.workordersystem.po.SubmitWorkorderToXStartPO[“filterStarttime”]) - 原因
LocalDateTime只能解析yyyy-MM-dd HH:mm:ss格式的时间,无法接收yyyy-MM-dd格式的数据.
10 获取json数据失败
- 异常
{
“timestamp”: “2020-06-18T03:57:12.698+0000”,
“status”: 500,
“error”: “Internal Server Error”,
“message”: “Error resolving template “api/workorder/userinfos”, template might not exist or might not be accessible by any of the configured Template Resolvers”,
“path”: “/api/workorder/userinfos”
} - 原因
未使用RestController或未添加ResponseBody. - 方案
使用RestController或添加ResponseBody.
【参考文献】
[1]https://www.jianshu.com/p/4ce077b15a2c
[2]https://www.cnblogs.com/xiaojf/p/11626500.html
[3]https://www.cnblogs.com/senlinyang/p/10430184.html
[4]https://stackoverflow.com/questions/42218237/java-lang-illegalargumentexception-invalid-character-found-in-method-name-http
[5]https://blog.csdn.net/qq_26899063/article/details/80611173
[6]https://blog.csdn.net/xiaozaq/article/details/54097720
[7]https://blog.csdn.net/zhanglf02/article/details/80436115
[8]http://www.cocoachina.com/articles/42418