SpringBoot获取自身tomcat端口号的坑 @Value("${server.port}")

今天在获取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

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值