Java 如何覆盖从spring PropertyPlaceHolderConfigure加载的特定属性?
我需要在运行时更改使用spring的PropertyPlaceHolderConfigure加载的选定配置属性的值。尝试了以下两种解决方案,但解决不了多少问题 解决方案1:在配置文件中使用PropertyOverrideConfiguler。提及 但该解决方案仅将值从覆盖的属性文件推送到所述bean的属性。但令人担忧的是,我得到了很多关于这个属性的消息。我只需要在一个地方重写运行时的默认值。这鼓励我选择下面的第二个解决方案 解决方案2:如前所述使用maven surefire插件 但我不会为了这个目的而使用任何surefire。是否有任何spring配置可以帮助我覆盖测试配置文件中的默认属性值Java 如何覆盖从spring PropertyPlaceHolderConfigure加载的特定属性?,java,spring,configuration,Java,Spring,Configuration,我需要在运行时更改使用spring的PropertyPlaceHolderConfigure加载的选定配置属性的值。尝试了以下两种解决方案,但解决不了多少问题 解决方案1:在配置文件中使用PropertyOverrideConfiguler。提及 但该解决方案仅将值从覆盖的属性文件推送到所述bean的属性。但令人担忧的是,我得到了很多关于这个属性的消息。我只需要在一个地方重写运行时的默认值。这鼓励我选择下面的第二个解决方案 解决方案2:如前所述使用maven surefire插件 但我不会为了这
谢谢。如果我不够清楚,请告诉我。使用覆盖属性文件怎么样?据我所知,我必须使用覆盖属性文件吗?如果是,这与n解决方案1中提到的类似。或者更确切地说,SPRING中是否有任何特定的机制来覆盖覆盖属性文件中的默认值。我建议的是,使用标准实践,SPRING可以从多个属性文件中读取属性,其中从以后的文件读取的属性覆盖从以前的文件读取的属性。这样的设置在春季很容易实现。如果这是您想要的,请告诉我。请解释您的答案以及您所做的更改。Gurum希望覆盖从PropertyPlaceHolderConfigure加载的属性。在我的代码中,我们可以打印/编辑/覆盖processProperties中加载的属性。就是这样,OP知道这个解决方案,他还要求别的什么?
You can use the below code to override properties, it will print out all the properties later on you can override whatever property you want:
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer {
private static Map<String, String> propertiesMap;
private static String keyToFind = "myProperty";
// Default as in PropertyPlaceholderConfigurer
private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;
@Override
public void setSystemPropertiesMode(int systemPropertiesMode) {
super.setSystemPropertiesMode(systemPropertiesMode);
springSystemPropertiesMode = systemPropertiesMode;
}
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
super.processProperties(beanFactory, props);
for (Object key : props.keySet()) {
String keyStr = key.toString();
if(keyStr.equals(keyToFind)) {
String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
System.out.println(valueStr);
}
}
}
public String getProperty(String name) {
return propertiesMap.get(name).toString();
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xm`enter code here`l");
((ConfigurableApplicationContext)context).close();
}
}