[英]Finding app base for embedded tomcat in spring boot
我正在使用彈簧靴。 我正在開發一個Web應用程序,我需要獲取應用程序庫才能生成電子郵件的鏈接。 為此,我需要獲取基本URL。 由於已嵌入tomcat,因此request.getContextpath()
返回null。 我需要動態獲取該localhost:8080
以便在將其部署到服務器時不必更改代碼。
在Spring Boot應用程序中,可以使用屬性server.context-path = your-path在application.properties中更改服務器上下文。
在您的代碼中,您可以參考以下屬性
@SpringBootApplication
@EnableConfigurationProperties(ServerProperties.class)
public class DemoApplication implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Autowired
ServerProperties serverProperties;
@Override
public void run(String... strings) throws Exception {
System.out.println("serverProperties.getContextPath(): " + serverProperties.getContextPath());
}
}
這里的關鍵點是在@Configuration
類上使用@EnableConfigurationProperties(ServerProperties.class)
,然后使用注入的字段ServerProperties消耗該值。
我希望這可以幫助您...
嗯,這花了我一些時間才能到達那里,但是:
@SpringBootApplication
public class TestServiceApplication {
public static void main(String[] args) {
AnnotationConfigEmbeddedWebApplicationContext context = (AnnotationConfigEmbeddedWebApplicationContext)SpringApplication.run(TestServiceApplication.class, args);
TomcatEmbeddedServletContainer tomcatContainer = (TomcatEmbeddedServletContainer)context.getEmbeddedServletContainer();
String host = tomcatContainer.getTomcat().getHost().getName();
int port = tomcatContainer.getPort();
System.out.println("Host:port " + host + ":" + port);
}
}
輸出: Host:port localhost:8080
那是你想要的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.