I'm experimenting with Netflix OSS for implementing a microservice architecture. I wanted to log server.port
from bootstrap.yml file at runtime to see which instance is serving the request.
I'm using Java8.
Important libraries versions are:
* spring-boot-starter-web-1.5.8
* spring-boot-starter-tomcat-1.5.8
* tomcat-embed-core-8.5.23
After browsing on stackoverflow, I found this and this but these solution did not work.
My bootstrap.yml looks like this:
spring:
application:
name: some-service
server:
port: ${port:8088}
I have tried following code:
@SpringBootApplication
@EnableEurekaClient
@SuppressWarnings("javadoc")
public class SomeService {
private static Logger logger = LoggerFactory.getLogger(SomeService .class);
@LocalServerPort
private static int randomServerPort;
@LocalManagementPort
private static int randomManagementPort;
@Autowired
private static Environment environment;
@Value("${server.port}")
// @Value("${local.server.port}")
private static int port;
public static void main(String[] args) {
SpringApplication.run(SomeService .class, args);
logger.info("randomServerPort : {}", randomServerPort);
logger.info("randomManagementPort : {}", randomManagementPort);
logger.info("server.port : {}", port);
logger.info("environment.getProperty(\"server.port\") : {}", environment.getProperty("server.port"));
}
Corresponding output is:
randomServerPort : 0
randomManagementPort : 0
server.port : 0
java.lang.NullPointerException against environment.getProperty("server.port")
First three log statements log 0
, while last one throws a `NullPointerException*.
At runtime, the port gets printed in logs on console as:
s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8088 (http)
I want to access this port number in main
method of SomeService
class. How can I do this?
Static fields are not injected in Spring.
What you need to do is making it an instance field first.
Then you have to use it only after that the Spring Boot container has initialized it.
Moving them in a method annotated with @PostConstruct
should do the job as this is invoked after that the dependency injection was performed.
@SpringBootApplication
@EnableEurekaClient
@SuppressWarnings("javadoc")
public class SomeService {
private static Logger logger = LoggerFactory.getLogger(SomeService .class);
@LocalServerPort
private static int randomServerPort;
@LocalManagementPort
private static int randomManagementPort;
@Autowired
private static Environment environment;
@Value("${server.port}")
private int port;
@PostConstruct
public void postConstruct(){
logger.info("randomServerPort : {}", randomServerPort);
logger.info("randomManagementPort : {}", randomManagementPort);
logger.info("server.port : {}", port);
logger.info("environment.getProperty(\"server.port\") : {}", environment.getProperty("server.port"));
}
public static void main(String[] args) {
SpringApplication.run(SomeService .class, args);
}
}