前言
由于在项目中启动的时候需要根据机器来动态获取ip的场景,所以想到了模仿springboot配置文件中类似${random.uuid} 这种配置的来支持,好了废话不多说,上代码。
1:定义功能类
这里我就简单写了个获取本机IP的
public class IPUtil {
public String getAddress() {
try {
InetAddress address = InetAddress.getLocalHost();
return address.getHostAddress();
} catch (UnknownHostException var1) {
return "0.0.0.0";
}
}
}
2:继承PropertySource编写自己的控制逻辑
public class IpValuePropertySource extends PropertySource<IPUtil> {
public static final String IPUTIL_PROPERTY_SOURCE_NAME = "ipUtil";
private static final String PREFIX = "ipUtil.";
public IpValuePropertySource(String name) {
super(name, new IPUtil());
}
@Override
public Object getProperty(String name) {
if (!name.startsWith(PREFIX)) {
return null;
}
return getAddress(name.substring(PREFIX.length()));
}
private String getAddress(String type){
if("local".equals(type)){
return getSource().getAddress();
}
return "0.0.0.0";
}
public static void addToEnvironment(ConfigurableEnvironment environment) {
environment.getPropertySources().addAfter(
StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
new IpValuePropertySource(IPUTIL_PROPERTY_SOURCE_NAME));
}
}
3:将自定义的PropertySource注入到spring环境中
3.1:继承ConfigFileApplicationListener覆写postProcessEnvironment方法
public class MyConfigFileApplicationListener extends ConfigFileApplicationListener {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
IpValuePropertySource.addToEnvironment(environment);
super.postProcessEnvironment(environment, application);
}
}
注意这里不能使用@Component之类注解注入,因为在springboot包中,已经在spring.factories中对ConfigFileApplicationListener进行了配置,导致优先级高于@ComponentScan
所以我们这里也使用spring.factories将我们自己的Listener交给spring
3.2:使用spring.factories将自定义Listeners注入spring中
# Application Listeners
org.springframework.context.ApplicationListener=\
com.zy.propertysource.demo.config.MyConfigFileApplicationListener
4:使用
4.1: 配置文件
testIp: ${ipUtil.local}
4.2: 测试代码
@RestController
public class TestController {
@Value("${testIp}")
private String ip;
@RequestMapping("/properties-test")
public String testBean(){
return ip;
}
}
4.3:效果