Skip to content

Instantly share code, notes, and snippets.

@joshlong
Created April 17, 2014 08:23
Show Gist options
  • Save joshlong/10964238 to your computer and use it in GitHub Desktop.
Save joshlong/10964238 to your computer and use it in GitHub Desktop.
Register this EmbeddedServletContainerCustomizer @bean in a Spring Boot application to customize the embedded Tomcat instance. In particular, this sets up SSL support for the container. I quite like this because it uses Java 8 lambas to nice effect. No finals, no anonymous inner classes. it just... works.
@Bean
EmbeddedServletContainerCustomizer containerCustomizer(
@Value("${keystore.file}") Resource keystoreFile,
@Value("${keystore.pass}") String keystorePass) throws Exception {
String absoluteKeystoreFile = keystoreFile.getFile().getAbsolutePath();
return (ConfigurableEmbeddedServletContainer container) -> {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
tomcat.addConnectorCustomizers(
(connector) -> {
connector.setPort(8443);
connector.setSecure(true);
connector.setScheme("https");
Http11NioProtocol proto = (Http11NioProtocol) connector.getProtocolHandler();
proto.setSSLEnabled(true);
proto.setKeystoreFile(absoluteKeystoreFile);
proto.setKeystorePass(keystorePass);
proto.setKeystoreType("PKCS12");
proto.setKeyAlias("tomcat");
}
);
}
};
}
@joshlong
Copy link
Author

@hho it's not enabled by default. That's something you still need to turn on at the container level. This example shows how to do so using embedded Tomcat. And Java 8.

@btiernay
Copy link

Shouldn't this be made easier with boot though? Wouldn't that be consistent with it's "value add"?

@ukimpact
Copy link

A single Bean... without a class. I keep struggling - the example is incomplete. Where this bean must be declared? In Application with main class? - Throws Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling.

How does this befriend @EnableAutoConfiguration?

What is the wrapper class? If I put it to separate configuration class then my changes are not picked up - ignored. Neither setPort works neither cookie max age.

Tried component wrapper, no way, the customizations are ignored. The entity is scanned..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment