edit: this answer is still correct, but see accepted answer for simpler solution.
EmbeddedTomcatConfiguration.java
package ...
import java.util.ArrayList;
import java.util.List;
import org.apache.catalina.connector.Connector;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EmbeddedTomcatConfiguration {
@Value("${server.additionalPorts}")
private String additionalPorts;
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
Connector[] additionalConnectors = this.additionalConnector();
if (additionalConnectors != null && additionalConnectors.length > 0) {
tomcat.addAdditionalTomcatConnectors(additionalConnectors);
}
return tomcat;
}
private Connector[] additionalConnector() {
if (StringUtils.isBlank(this.additionalPorts)) {
return null;
}
String[] ports = this.additionalPorts.split(",");
List<Connector> result = new ArrayList<>();
for (String port : ports) {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(Integer.valueOf(port));
result.add(connector);
}
return result.toArray(new Connector[] {});
}
}
application.yml
server:
port: ${appPort:8800}
additionalPorts: 8880,8881
Application.java
@SpringBootApplication
@ComponentScan(...)
@Import(EmbeddedTomcatConfiguration.class)
public Application {
public static void main(String[] args) {
SpringApplication.run(Application .class, args);
}
}
and my suggestion for limiting accessing javamelody from a specific port would be to extend the javamelody filter and just chain the request if it comes from a specific port otherwise send back a 404.
From the logs:
INFO TomcatEmbeddedServletContainer:185 - Tomcat started on port(s): 8800 (http) 8880 (http) 8881 (http)
This approach BTW exposes other endpoints on these ports.
To solve this and limiting javamelody filter (/monitoring) to a specific port, you would need to write a filter that verifies path (servlet and filter path) being requested from allowable ports keeping in mind that the ordering of these filters is important.
Based on this answer and partial source code that I had already available when I answered this question, I had published a blog post about this topic at http://tech.asimio.net/2016/12/15/Configuring-Tomcat-to-Listen-on-Multiple-ports-using-Spring-Boot.html