Adding embedded Tomcat AJP support to a Spring Boot application

We currently use Apache with mod_jk in front of our Tomcat application servers. I was exploring how to use an embedded Tomcat while enabling an AJP connector. I wanted all the configuration to be property driven, allow the specification of HTTP/AJP ports, and allow the switching off of AJP for running the app locally.

Here’s how I went about it.

Application class

Firstly in the Spring Boot Application class you can tell the application on startup to use custom settings for the embedded Tomcat. Out of the box if you specify server.port as a property it will change the port of the standard http connector. I specified that property and some other values specific to AJP.

server.port=8082
tomcat.ajp.port=9090
tomcat.ajp.remoteauthentication=false
tomcat.ajp.enabled=true

They were then wired into the Application class using @Value annotations. The server.port is already handled by Spring Boot so I don’t have to do anything.

@Value("${tomcat.ajp.port}")
int ajpPort;

@Value("${tomcat.ajp.remoteauthentication}")
String remoteAuthentication;

@Value("${tomcat.ajp.enabled}")
boolean tomcatAjpEnabled;

Then I added in a specific Bean which defines the Tomcat settings, and whether or not to switch on AJP based on a property being set.

@Bean
public EmbeddedServletContainerFactory servletContainer() {

    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    if (tomcatAjpEnabled)
    {
        Connector ajpConnector = new Connector("AJP/1.3");
        ajpConnector.setProtocol("AJP/1.3");
        ajpConnector.setPort(ajpPort);
        ajpConnector.setSecure(false);
        ajpConnector.setAllowTrace(false);
        ajpConnector.setScheme("http");
        tomcat.addAdditionalTomcatConnectors(ajpConnector);
    }

    return tomcat;
}

Then when I start up the application, I end up with an HTTP connector running on a specific port, and also optionally an AJP connector running on a specific port.

2015-06-24 08:40:09.514 INFO 93685 --- [ main] org.apache.coyote.ajp.AjpNioProtocol : Initializing ProtocolHandler ["ajp-nio-9090"]
2015-06-24 08:40:09.516 INFO 93685 --- [ main] org.apache.coyote.ajp.AjpNioProtocol : Starting ProtocolHandler ["ajp-nio-9090"]
2015-06-24 08:40:09.521 INFO 93685 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8082 (http) 9090 (http)
2015-06-24 08:40:09.523 INFO 93685 --- [ main] uk.ac.ed.ca.centralauthms.Application : Started Application in 4.178 seconds (JVM running for 4.6)