Код: Выделить всё
/**
* Simple Spring Boot test with a web environment which should listening on random port.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class OnOfTheTestClassses {
@LocalServerPort
private int localPort;
@Test
public void localPort() {
// Should output random port but actually outputs the default of the Tomcat container
Assertions.assertNotEquals(8080, localPort, "Tomcat is listening on default port which is not expected");
}
}
Код: Выделить всё
/**
* Simple bean for test purposes. The bean needs the port Tomcat is listening on.
*/
@Component
public class DemoTestBean {
@Autowired
private WebServerApplicationContext webServerAppCtxt;
// Disabling the annotation so tomcat will listen only on random port
@PostConstruct
public int getPort() {
// In the @PostConstruct phase the property local.server.port isn't set.
// To get a port the bean uses the web server context.
// This causes tomcat listening on two ports: 8080 and a random port.
// Output: Tomcat started on port(s): 8080 (http) > (http)
return webServerAppCtxt.getWebServer().getPort();
}
}
Первое, что я обнаружил. заключалось в том, что Tomcat прослушивает два порта: 8080 и случайный порт, см. следующий журнал:
Код: Выделить всё
com.example.demo.DemoApplicationTests : Starting DemoApplicationTests using Java 11.0.11 on ME1280 with PID 116328 (started by
com.example.demo.DemoApplicationTests : No active profile set, falling back to 1 default profile: "default"
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
o.apache.catalina.core.StandardService : Starting service [Tomcat]
org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.62]
o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1404 ms
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) 45719 (http) with context path ''
com.example.demo.DemoApplicationTests : Started DemoApplicationTests in 2.696 seconds (JVM running for 4.612)
После некоторых проб и ошибок с аннотациями Spring Boot и конфигурациях я нашел виновника. Метод @PostConstruct заставляет Tomcat прослушивать порт 8080.
Мне кажется, что внедренный WebServerApplicationContext не ссылается на прослушивает экземпляр tomcat и создает новый экземпляр Connector с портом по умолчанию, когда webServerAppCtxt.getWebServer().getPort() вызывается в методе @PostConstruct. Почему он так себя ведет?
Рабочий пример можно найти здесь. Простая проверка и сборка с помощью maven или предпочитаемой вами IDE. Пример теста завершится неудачно, если Tomcat прослушивает порт по умолчанию 8080.
Подробнее здесь: https://stackoverflow.com/questions/721 ... n-postcons