java - 部署在 Tomcat 上的 WAR 文件未读取 application.properties 文件
问题描述
我使用 Java 中的 Spring Boot Framework 创建了一个演示 REST API。我想将此 API 作为 WAR 文件部署在 Tomcat 8 上。API 已经配置为使用 Spring Initializr 编译为 WAR 文件。但是,在部署 API 时,它不会application.properties
从项目中读取文件。
- 我已经尝试过使用
@PropertySource
和@PropertySources
注释。 - 我还尝试在 pom.xml 文件的标签中包含
<resources>
标签。<build>
- 我也试过添加
.properties("classpath:application.properties")
到ServletInitializer
没有任何效果
更新
我在这篇文章中使用了上下文路径作为示例。在我的实际应用程序中,我有一些属性存储在 application.properties 并且应用程序没有读取它们。
这是我的代码文件:
- 应用程序属性
server.servlet.context-path=/api
- 应用程序.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- ServletInitializer.java
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
- 用户.java
@RestController
@RequestMapping("/user")
public class User {
@GetMapping("")
public String getUser() {
return "User is here...";
}
}
点击localhost:8080/demo/api/user
URL 应该会给出我们想要的输出,但它会给出 404 结果。然而,击球localhost:8080/demo/user
正在提供所需的输出。这意味着应用程序没有读取 application.properties 文件,因为 api 的默认路由/api
在该文件中设置为。
解决方案
只有嵌入式 tomcat 支持server.servlet.context-path
. 如果您要部署到外部 tomcat,请按照此处的指南设置上下文路径:https ://tomcat.apache.org/tomcat-8.0-doc/config/context.html
现在,验证是否application.properties
捆绑在WAR
文件中。为此,请提取或打开WAR
文件。如果未包含,则验证您的构建文件是否资源插件正在复制资源文件。
如果application.properties
WAR 中包含 ,请尝试读取应用程序中的其他属性。
推荐阅读
- python - Plot histogram for feature of array with known and limited values
- java - 如何在grails中制作方法POST?
- ios - How use alert and spinner in same class?
- spring-boot - Spring Boot、Spring 会话、JDBC
- c++ - 如何修复“CMAKE_CXX_COMPILER: cl 不是完整路径且未在 PATH 中找到”。错误?
- elasticsearch - 如何比较两个 elastcsearch 集群文档计数
- corda - 在corda shell中将状态对象作为参数传递
- java - 如何在 Spring RESTful Web 服务中缓存用户角色详细信息?
- asp.net-core - 如何在 asp.net 核心应用程序的配置中为 docker-compose vars 使用 .env 文件?
- android - Cordova android 加载资源失败:net::ERR_FILE_NOT_FOUND