2

I have a generic java agent based on aspectj which runs on several spring boot applications (and several spring boot versions). I'm trying to find a way to get the port on runtime, programatically when the application STARTS (before a request is made). The problem -

  1. I cannot use the regular way to get a spring boot port such as the ones described in https://stackoverflow.com/questions/30312058/spring-boot-how-to-get-the-running-port which includes @Autowired annotation etc.

  2. I'm looking for the port after the applications starts, without relying on requests to be made.

I'm looking for a way to access the LocalServerPort object or any other options that will allow me to access the port.

thanks for any help

Lin
  • 2,445
  • 5
  • 27
  • 37
  • This sounds like a questionably hacky situation (it's usually better to *tell* the application what port to use), but you could try something with a static holder and a runner that sets a value there. – chrylis -cautiouslyoptimistic- Oct 16 '18 at 09:06
  • `@LocalServerPort` is only for tests and not runtime. So trying to get that at runtime will simply fail because it isn't there (it is test only!). The agent should get the `ServerProperties` and look at the `port` if that has been set use it else use the default `8080`. However still feels hacky and looks like you are trying to do things at the wrong location. – M. Deinum Oct 16 '18 at 09:18
  • @chrylis it is indeed not a standard case, but rather a tricky one...Can you give me an example of what you mean by a static holder and a runner? – Lin Oct 16 '18 at 10:33

1 Answers1

0

After some investigation, as I mentioned I'm working with aspectj,I used the following instrumentation:

 after():
         execution(org.springframework.boot.context.embedded.EmbeddedServletContainer+.new(..))

And took the port directly from the EmbeddedServletContainer instance using the getPort() method. In case of Tomcat, if the port is -1, I use the embedded tomcat object to get the port from the connector itself.

Lin
  • 2,445
  • 5
  • 27
  • 37