!253 refactor 优化 InetUtilsProperties 的绑定逻辑,避免早期初始化问题

* refactor 优化 InetUtilsProperties 的绑定逻辑,避免早期初始化问题
This commit is contained in:
xuyuefeng
2026-01-13 08:16:46 +00:00
committed by 疯狂的狮子Li
parent 13db835165
commit 7bf5118a11

View File

@@ -5,11 +5,10 @@ import org.dromara.common.core.utils.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
@@ -21,7 +20,20 @@ import java.net.InetAddress;
*
* @author Lion Li
*/
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered, EnvironmentAware {
private Environment environment;
/**
* 设置此组件运行的应用环境。
* 由 Spring 容器回调注入。
*
* @param environment 当前应用环境对象
*/
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
/**
* 获取该 BeanFactoryPostProcessor 的顺序,确保它在容器初始化过程中具有最高优先级
@@ -45,13 +57,14 @@ public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor,
if (StringUtils.isNotBlank(property)) {
return;
}
// 获取 InetUtils bean用于获取 IP 地址
Environment environment = beanFactory.getBean(Environment.class);
InetUtilsProperties target = new InetUtilsProperties();
ConfigurationPropertySources.attach(environment);
Binder.get(environment).bind(InetUtilsProperties.PREFIX, Bindable.ofInstance(target));
String ip = "127.0.0.1";
try (InetUtils inetUtils = new InetUtils(target)) {
// 手动绑定 InetUtilsProperties避免早期初始化导致配置未注入
InetUtilsProperties properties = Binder.get(environment)
.bind(InetUtilsProperties.PREFIX, InetUtilsProperties.class)
.orElseGet(InetUtilsProperties::new);
// 创建临时的 InetUtils 实例
try (InetUtils inetUtils = new InetUtils(properties)) {
String ip = "127.0.0.1";
// 获取第一个非回环地址
InetAddress address = inetUtils.findFirstNonLoopbackAddress();
if (address != null) {
@@ -68,8 +81,8 @@ public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor,
ip = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
}
}
// 设置系统属性 DUBBO_IP_TO_REGISTRY 为获取到的 IP 地址
System.setProperty(CommonConstants.DubboProperty.DUBBO_IP_TO_REGISTRY, ip);
}
// 设置系统属性 DUBBO_IP_TO_REGISTRY 为获取到的 IP 地址
System.setProperty(CommonConstants.DubboProperty.DUBBO_IP_TO_REGISTRY, ip);
}
}