Java 如何在 Spring Boot 中获取本地服务器主机和端口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29929896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get local server host and port in Spring Boot?
提问by Abdull
I'm starting up a Spring Boot application with mvn spring-boot:run
.
我正在使用mvn spring-boot:run
.
One of my @Controller
s needs information about the host and port the application is listening on, i.e. localhost:8080
(or 127.x.y.z:8080
). Following the Spring Boot documentation, I use the server.address
and server.port
properties:
我@Controller
的其中一个需要有关应用程序正在侦听的主机和端口的信息,即localhost:8080
(或127.x.y.z:8080
)。按照Spring Boot 文档,我使用server.address
和server.port
属性:
@Controller
public class MyController {
@Value("${server.address}")
private String serverAddress;
@Value("${server.port}")
private String serverPort;
//...
}
When starting up the application with mvn spring-boot:run
, I get the following exception:
使用 启动应用程序时mvn spring-boot:run
,出现以下异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: ... String ... serverAddress; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'server.address' in string value "${server.address}"
Both server.address
and server.port
cannot be autowired.
双方server.address
并server.port
不能自动装配。
How can I find out the (local) host/address/NIC and port that a Spring Boot application is binding on?
如何找出 Spring Boot 应用程序绑定的(本地)主机/地址/网卡和端口?
回答by Kiwi
IP Address
IP地址
You can get network interfaces with NetworkInterface.getNetworkInterfaces()
, then the IP addresses off the NetworkInterface objects returned with .getInetAddresses()
, then the string representation of those addresses with .getHostAddress()
.
您可以使用 获取网络接口NetworkInterface.getNetworkInterfaces()
,然后是返回的 NetworkInterface 对象的 IP 地址.getInetAddresses()
,然后是这些地址的字符串表示形式.getHostAddress()
。
Port
港口
If you make a @Configuration
class which implements ApplicationListener<EmbeddedServletContainerInitializedEvent>
, you can override onApplicationEvent
to get the port number once it's set.
如果您创建一个@Configuration
实现的类ApplicationListener<EmbeddedServletContainerInitializedEvent>
,则可以在设置后重写onApplicationEvent
以获取端口号。
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
int port = event.getEmbeddedServletContainer().getPort();
}
回答by azizunsal
You can get port info via
您可以通过以下方式获取端口信息
@Value("${local.server.port}")
private String serverPort;
回答by medge
One solution mentioned in a reply by @M. Deinum is one that I've used in a number of Akka apps:
@M 在回复中提到的一种解决方案。Deinum 是我在许多 Akka 应用程序中使用过的:
object Localhost {
/**
* @return String for the local hostname
*/
def hostname(): String = InetAddress.getLocalHost.getHostName
/**
* @return String for the host IP address
*/
def ip(): String = InetAddress.getLocalHost.getHostAddress
}
I've used this method when building a callback URL for Oozie REST so that Oozie could callback to my REST service and it's worked like a charm
我在为 Oozie REST 构建回调 URL 时使用了此方法,以便 Oozie 可以回调到我的 REST 服务,并且它的工作原理非常棒
回答by Enrico Giurin
An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequestin the signature of one of the controller's methods. Once you have the HttpServletRequestinstance is straightforward to get the baseUrl with this: request.getRequestURL().toString()
一个简单的解决方法,至少要获取正在运行的端口,是在控制器方法之一的签名中添加参数javax.servlet.HttpServletRequest。一旦你有了HttpServletRequest实例,就可以直接通过以下方式获取 baseUrl:request.getRequestURL().toString()
Have a look at this code:
看看这个代码:
@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO,
HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}
回答by Sen
To get the port number in your code you can use the following:
要获取代码中的端口号,您可以使用以下命令:
@Autowired
Environment environment;
@GetMapping("/test")
String testConnection(){
return "Your server is up and running at port: "+environment.getProperty("local.server.port");
}
To understand the Environment property you can go through this Spring boot Environment
要了解 Environment 属性,您可以通过此 Spring boot Environment
回答by vargapeti
I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.
我刚刚找到了一种使用 Eureka 客户端库轻松获取服务器 IP 和端口的方法。由于我无论如何都将它用于服务注册,因此它不是仅用于此目的的附加库。
You need to add the maven dependency first:
需要先添加maven依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
Then you can use the ApplicationInfoManager service in any of your Spring beans.
然后您可以在任何 Spring bean 中使用 ApplicationInfoManager 服务。
@Autowired
private ApplicationInfoManager applicationInfoManager;
...
InstanceInfo applicationInfo = applicationInfoManager.getInfo();
The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.
InstanceInfo 对象包含有关您的服务的所有重要信息,例如 IP 地址、端口、主机名等。
回答by Renetik
For Spring 2
春季 2
val hostName = InetAddress.getLocalHost().hostName
var webServerPort: Int = 0
@Configuration
class ApplicationListenerWebServerInitialized : ApplicationListener<WebServerInitializedEvent> {
override fun onApplicationEvent(event: WebServerInitializedEvent) {
webServerPort = event.webServer.port
}
}
then you can use also webServerPort
from anywhere...
那么你也可以webServerPort
从任何地方使用......
回答by lemonzone2010
You can get hostname from spring cloud property in spring-cloud-commons-2.1.0.RC2.jar
您可以从 spring-cloud-commons-2.1.0.RC2.jar 中的 spring cloud 属性获取主机名
environment.getProperty("spring.cloud.client.ip-address");
environment.getProperty("spring.cloud.client.hostname");
spring.factories of spring-cloud-commons-2.1.0.RC2.jar
spring-cloud-commons-2.1.0.RC2.jar的spring.factories
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor
回答by CuriousDev
I used to declare the configuration in application.properties
like this (you can use you own property file)
我以前是这样声明配置的application.properties
(你可以使用你自己的属性文件)
server.host = localhost
server.port = 8081
and in application you can get it easily by @Value("${server.host}")
and @Value("${server.port}")
as field level annotation.
在应用程序,您可以通过轻松得到它@Value("${server.host}")
,并@Value("${server.port}")
为现场级的注释。
or if in your case it is dynamic than you can get from system properties
或者如果在您的情况下它是动态的,而不是您可以从系统属性中获得
Here is the example
这是例子
@Value("#{systemproperties['server.host']}")
@Value("#{systemproperties['server.port']}")
@Value("#{systemproperties['server.host']}")
@Value("#{systemproperties['server.port']}")
For a better understanding of this annotation , see this example Multiple uses of @Value annotation
为了更好地理解这个注解,请看这个例子@Value注解的多次使用