在Java 8中,如何在不在我的环境中对其进行硬编码的情况下获取主机名? [英] In Java 8, how do I get my hostname without hard-coding it in my environment?

查看:136
本文介绍了在Java 8中,如何在不在我的环境中对其进行硬编码的情况下获取主机名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们刚刚在Amazon Linux上升级到Java 8。我们正在使用Spring 4.3.8.RELEASE。过去我们可以通过在我们的应用程序上下文文件中设置bean来获取我们的机器主机名,如此...

We just upgraded to Java 8 on Amazon Linux. We are using Spring 4.3.8.RELEASE. It used to be that we could get our machine hostname by setting up beans in our application context file like so ...

<bean id="localhostInetAddress" class="java.net.InetAddress" factory-method="getLocalHost" />
<bean id="hostname" factory-bean="localhostInetAddress" factory-method="getHostName" />

但是对于Java 8,beanhostname现在包含字符串

But with Java 8, the bean "hostname" now contains the string

localhost

Java 8之前,它用于包含在命令行上运行的主机名值,这是

Before Java 8, it used to contain the "hostname" value as run on the command line, which is

[myuser@machine1 ~]$ hostname
machine1.mydomain.org

如何重新配置​​我们的bean以便它获得命令行列出的主机名?我不想在任何地方进行任何硬编码。

How can I reconfigure our bean so that it gets the hostname that the command line lists out? I don't want to hard-code anything anywhere.

推荐答案

OpenJDK错误


较新的调用遵循localhosts /etc/nsswitch.conf配置文件。对于这台机器,该文件告诉这些
调用在引用其他命名服务之前查看文件。

The newer calls respect the localhosts /etc/nsswitch.conf configuration files. In the case of this machine that file tells these calls to look in files before referencing other naming services.

因为/ etc / hosts文件包含一个显式的这个
主机名/ IP组合的映射,即返回的内容。

Since the /etc/hosts file contains an explicit mapping for this hostname / IP combination, that is what is returned.

在较旧的JDK中,gethostbyname实际上忽略了本地
机器设置和立即委托给命名服务。

In the older JDK's the gethostbyname actually ignored the local machines settings and immediately delegated to the naming service.

您可以随时使用 运行时 类:

You can always use the Runtime class for that :

Process hostname = Runtime.getRuntime().exec("hostname");

BufferedReader stdInput = new BufferedReader(new
            InputStreamReader(hostname.getInputStream()));
String s;
while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
}

但不建议你这样做see

这篇关于在Java 8中,如何在不在我的环境中对其进行硬编码的情况下获取主机名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆