java - 在 spring boot 中查找嵌入式 tomcat 的应用程序库

标签 java spring spring-mvc tomcat spring-boot

我正在使用 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/

相关文章:

java - 如何在 Android 应用程序中使用 XML 播放歌曲?

java - Android调用数组列表导致程序崩溃

java - 服务器端的 webSockets 连接管理

java - 如何在JHipster中为FeignClient启用Autowired?

java - 从另一个 Maven 项目加载消息属性

java - 如何使用 spring NamedParameterJdbcTemplate 从存储过程中检索数据?

spring-mvc - 构造函数抛出异常;嵌套异常是 java.lang.NoSuchMethodError : org. springframework.util.AntPathMatcher.setCaseSensitive(Z)V

java - Spring CrudRepository 不工作保存和删除操作

jsf - 如何在 Spring-MVC 和 JSF 混合 Web 应用程序中设置 JSF 欢迎文件

java - 如何有效地找到一个圆圈、一个网格中的所有 block ?