我正在使用 Spring Boot 。我正在开发一个 Web 应用程序,我需要获取应用程序库来生成电子邮件链接。为此,我需要获取基本 URL。由于嵌入了tomcat
request.getContextpath()
返回空值。我需要动态获取 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)
,然后使用注入(inject)的字段 ServerProperties 来使用该值。
希望对您有所帮助...
关于java - 在 spring boot 中查找嵌入式 tomcat 的应用程序库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36590903/