PropertyPlaceholderConfigurer:我可以拥有动态位置值
现在我在我的xml文件中有这个:
和
file:C:/jdbc.properties
现在,我的问题是我不知道这个文件的确切位置(jdbc.properties),因为这个应用程序将在不同的计算机上运行,在某些地方它安装在c:中,有时可能在f:..所以,如果我不知道这个文件的路径,无论如何我都能找到它。
谢谢
您可以将文件位置定义为系统属性,例如-Dprops.file = file:c:/1.properties
$props.file
要么
或者您可以扫描文件系统
class ScanningPropertyPlaceholderConfigurer extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer { public void setFileName(String fileName) throws FileNotFoundException { File file = findFile(fileName); // implement file finder super.setLocation(new FileSystemResource(file)); }
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); configurer.setLocation(new ClassPathResource("context.properties")); ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}, false); applicationContext.addBeanFactoryPostProcessor(configurer); applicationContext.refresh();
是。 您可以让Spring
在类路径中找到该文件。 该文件可以存在于不同计算机上的不同位置,但只要它存在于类路径中就会加载。
classpath:jdbc.properties
可以有多种方法来处理它。
- 将文件放在项目中,这样您将始终拥有相同的相对路径。
- 在构建期间填充值,即将占位符放在值标记中,并在构建期间通过传递参数替换它。 例如,如果您使用ant来进行构建,则可以使用
expandproperties
任务来执行此操作。