我想根据提供的网络接口创建一个包含运行系统MAC地址的单例。
我写了以下代码:
public class NodeMac {
private static final String INSTANCE = getMacAddress();
private static String networkInterfaceName;
@Value("${machine.network.interface}")
public void setNetworkInterfaceName(String networkInterfaceName) {
NodeMac.networkInterfaceName = networkInterfaceName;
}
private NodeMac() { }
public static String getInstance() {
return INSTANCE;
}
private static String getMacAddress() {
try {
NetworkInterface network = NetworkInterface.getByName(networkInterfaceName);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return sb.toString();
} catch (SocketException | NullPointerException e) {
throw new RuntimeException(
"Failed to extract MAC address for network interface with name " + networkInterfaceName, e);
}
}
}
在application.properties中:
machine.network.interface=eno1
但是,我找不到任何方法来获取包含网络接口名称的属性值。无论我如何尝试访问它,它始终为null。
这样做的正确方法是什么?在单身人士中拥有属性是一种反模式吗?
答案 0 :(得分:1)
修改强>
所以你正在努力用注入的@Value创建单实例pojo类。如果你可以使用bean,那么这就是要走的路:
@Component // This will default give you a single ton bean
public class NodeMac {
@Value("${machine.network.interface}")
private String networkInterfaceName;
public String getMacAddress() {
try {
NetworkInterface network = NetworkInterface.getByName(networkInterfaceName);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return sb.toString();
} catch (SocketException | NullPointerException e) {
throw new RuntimeException(
"Failed to extract MAC address for network interface with name " + networkInterfaceName, e);
}
}
}
<强> OLD 强>
你怎么想出这个表达方式:
String key = System.getProperty("machine.network.interface");
该机器不太可能只有一个网络接口,因此无法返回单个密钥。
确实,oracle已经写了tutorial here
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}