我需要在运行时更改所选配置属性的值,这些属性是使用spring的PropertyPlaceHolderConfigurer加载的。尝试了两个解决方案,但是解决了很多,
解决方案1:在配置文件中使用PropertyOverrideConfigurer。提到here
但是这个解决方案只将值从overriden属性文件推送到提到的bean的属性。但值得关注的是,我有很多豆子指的是这个属性。我需要在运行时在一个地方覆盖默认值。这鼓励我在下面找到第二个解决方案。
解决方案2:使用提到的here.
的maven surefire插件但我并不是为了这个唯一目的而使用任何万无一失。是否有任何弹簧配置可以帮助我覆盖测试配置文件中的默认属性值。
感谢。如果我不够清楚,请告诉我。
答案 0 :(得分:-2)
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();
}
}