今天在获取springboot自带端口时遇到一个坑,找了好久,故此记录一下。
首先 @Value("${server.port}") 获取端口号没有任何问题,那么问题出在那呢,出在单元测试中!!!
你在单元测试中,调用的类或者方法这个地方获取到的端口号就会变成-1。
解决办法:在后面加上下属性
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
原理:
org.springframework.boot.test.context.SpringBootContextLoader#getInlinedProperties
protected String[] getInlinedProperties(MergedContextConfiguration config) {
ArrayList<String> properties = new ArrayList<String>();
// JMX bean names will clash if the same bean is used in multiple contexts
disableJmx(properties);
properties.addAll(Arrays.asList(config.getPropertySourceProperties()));
if (!isEmbeddedWebEnvironment(config) && !hasCustomServerPort(properties)) {
properties.add("server.port=-1");
}
return properties.toArray(new String[properties.size()]);
}
感谢某些大佬,大家可以参照:
https://stackoverflow.com/questions/46684818/springboot-test-valueserver-port