Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: specify port at the mapping level

Spring Boot: I want to have achieved the following: some URL paths are mapped to a port, some to another.

In other words I'd like something like:

public class Controller1 {
  @RequestMapping(value="/path1", port="8080") public...
  @RequestMapping(value="/path2", port="8081") public...
}

So that my app responds to both localhost:8080/path1 and localhost:8081/path2

It's acceptable to have 2 separate controllers within the app.

I have managed to partially succeed by implementing an EmbeddedServletContainerCustomizer for tomcat, but it would be nice to be able to achieve this inside the controller if possible.

Is it possible?

like image 372
Diego Martinoia Avatar asked Sep 14 '16 15:09

Diego Martinoia


2 Answers

What you are trying to do would imply that the application is listening on multiple ports. This would in turn mean that you start multiple tomcat, since spring-boot packages one container started on a single port.

What you can do

You can launch the same application twice, using different spring profiles. Each profile would configure a different port.

2 properties:

application-one.properties: server.port=8080

application-two.properties: server.port=8081

2 controllers

@Profile("one")
public class Controller1 {
  @RequestMapping(value="/path1") public...
}

@Profile("two")
public class Controller2 {
  @RequestMapping(value="/path2") public...
}

Each controller is activated when the specified spring profile is provided.

Launch twice

$ java -jar -Dspring.profiles.active=one YourApp.jar
$ java -jar -Dspring.profiles.active=two YourApp.jar
like image 166
alexbt Avatar answered Sep 28 '22 18:09

alexbt


While you cannot prevent making call on the undesired port, you can specify HttpServletRequest among other parameters of the method of the controller, and then use HttpServletRequest.getLocalPort() to obtain the port the call is made on.

Then you can manually return the HTTP error code if the request is made on the wrong port, or forward to another controller if the design is such that same path on different ports must be differently processed.

like image 44
Audrius Meškauskas Avatar answered Sep 28 '22 18:09

Audrius Meškauskas