問題描述:
Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value '1-1'; nested exception is java.lang.NumberFormatException: For input string: "1-1"
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:46)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:191)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174)
at org.springframework.core.env.AbstractPropertyResolver.convertValueIfNecessary(AbstractPropertyResolver.java:263)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:91)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:68)
at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:546)
at org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType.getPortProperty(ManagementPortType.java:57)
at org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType.get(ManagementPortType.java:46)
at org.springframework.boot.actuate.autoconfigure.web.server.OnManagementPortCondition.getMatchOutcome(OnManagementPortCondition.java:53)
現(xiàn)象:正常運(yùn)行工程卻是沒報(bào)錯(cuò),估計(jì)是@Test運(yùn)行的時(shí)候哪些properties沒有成功加載
分析:
全局搜索“1-1”,沒有搜索到相關(guān)字符串
根據(jù)上述堆棧代碼:
OnManagementPortCondition.getMatchOutcome(OnManagementPortCondition.java:53)
定位到是在依賴庫:
compile('de.codecentric:spring-boot-admin-starter-client')中的
先將其注釋掉,可以正常跑Test了。
說明問題與這個(gè)庫相關(guān);
根據(jù)上述堆棧進(jìn)行Debug, 調(diào)試真的很重要,下斷點(diǎn)調(diào)試:
定位如下代碼片段:
static ManagementPortType get(Environment environment) {
Integer serverPort = getPortProperty(environment, "server.");
Integer managementPort = getPortProperty(environment, "management.server.");
private static Integer getPortProperty(Environment environment, String prefix) {
return environment.getProperty(prefix + "port", Integer.class);
}
調(diào)試發(fā)現(xiàn)這個(gè)port讀取到的值居然是-1,而且讀取properties中的字段“management.server.port”
打開application.yml配置文件進(jìn)行查看
############################actuator配置#######################################
management:
endpoints:
web:
exposure:
include: "*" #“*”號(hào)代表啟用所有的監(jiān)控端點(diǎn),可以單獨(dú)啟用,例如,health,info,metrics等
server:
servlet:
context-path:
ssl:
enabled: false
port: 1${server.port} # actuator訪問的端口
endpoint:
上述是yaml的配置寫法,具體可以查看yaml語法,上述port的寫法拼接起來就是:
"management.server.port" 對(duì)應(yīng)前面源碼中的字段key值。
而且配置文件中的配置寫法是 1${server.port}
之前調(diào)試發(fā)現(xiàn)獲取到的屬性值是 -1 這就能解釋報(bào)錯(cuò)“1-1”的問題了,源碼中port是默認(rèn)Integer類型的,但現(xiàn)在通過屬性讀取后是“1-1” 便出現(xiàn)類型轉(zhuǎn)換錯(cuò)誤。
正常跑程序是ok的,而跑@Test測(cè)試用例則不行,估計(jì)是跑@Test加載程序的時(shí)候,有一些配置沒有初始化到,而下面的{server.port}用到的是前面配置的結(jié)果(僅僅猜測(cè),剛剛學(xué)習(xí),后續(xù)研究下單元測(cè)試的初始化流程)
總結(jié):遇到問題先分析,根據(jù)堆棧進(jìn)行調(diào)試,Debug the Code! ^_^