[英]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.