Search code examples
javaspringspring-boottomcattomcat8

WAR file deployed on Tomcat not reading application.properties File


I've created a Demo REST API using Spring Boot Framework in Java. I wanted to deploy this API on Tomcat 8 as a WAR file. The API is already configured to compile down as a WAR file using Spring Initializr. But, when the API is deployed, its not reading application.properties file from the project.

  • I've already tried using @PropertySource and @PropertySources annotations.
  • I've also tried including <resources> tag in <build> tag in pom.xml file.
  • I've also tried adding .properties("classpath:application.properties") to ServletInitializer

Nothing worked


Update

I've used context-path as an example in this post. In my actual application, I have some properties stored in application.properties and the application is not reading them.


Here's my code files:

  • application.properties
server.servlet.context-path=/api
  • Application.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);
    }
}
  • User.java
@RestController
@RequestMapping("/user")
public class User {

    @GetMapping("")
    public String getUser() {
        return "User is here...";
    }
}

Hitting localhost:8080/demo/api/user URL should give our desired output, but its rather giving a 404 result. Whereas, hitting localhost:8080/demo/user is giving the desired output. This means that the applicaiton is not reading application.properties file because the default route of the api was set to /api in that file.


Solution

  • Only embedded tomcat honors the server.servlet.context-path. If you are deploying to an external tomcat, follow the guidelines here to set the context path: https://tomcat.apache.org/tomcat-8.0-doc/config/context.html

    Now, verify whether application.properties is bundled in the WAR file. To do this extract or open the WAR file. If not included then verify your build file whether resource plugin is copying the resource files.

    If the application.properties is included in the WAR then, try reading other properties in your application.