springboot-How to deploy springboot web applications to apache tomcat?

1. The purpose of this post

I would demo how to build and deploy springboot web applications to apache tomcat.

2. Environments

  • SpringBoot 2.x
  • Thymeleaf 3.x

3. Key points

3.1 change your pom.xml

  • Change embeded tomcat to provided tomcat:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-tomcat</artifactId>
  <scope>provided</scope>
</dependency>
  • package your project as war
<packaging>war</packaging>
<!-- if you do not have a web.xml in your springboot project,you should add this plugin -->
<build>
     <plugins>
          <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
     </plugins>
</build>

3.2 change your entry application class

Change your entry main class of springboot application to extends the SpringBootServletInitializer like this:

@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApplication.class);
    }
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class,args);
    }
}

3.3 Externalize your application configuration files

If you want to externalize the configuration properties file of your web application, you can just do like this:

  • Put your configuration file(application.properties) to your tomcat webconfig directory
    • mkdir webconfig in your tomcat root dir
    • cp your application.properties file to the webconf dir and remember its path
  • change your catalina.sh like this:
JAVA_OPTS="$JAVA_OPTS -Dspring.config.additional-location=/your_path_to_apache-tomcat-9.0.27/webconfig/application.properties"

3.4 Failed to get driver instance for jdbcUrl exception

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.RuntimeException: Failed to get driver instance for jdbcUrl=jdbc:postgresql://10.1.1.1:5432/northwind

Caused by: java.lang.RuntimeException: Failed to get driver instance for jdbcUrl=jdbc:postgresql://10.1.1.1:5432/northwind

Add this line to your application.properties:

spring.datasource.driver-class-name=org.postgresql.Driver