Java PropertyPlaceHolderConfigure:我可以有一个动态位置值吗
现在,我的xml文件中有以下内容:Java PropertyPlaceHolderConfigure:我可以有一个动态位置值吗,java,Java,现在,我的xml文件中有以下内容: <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/dashboardsupervisor" />
<property name="username" value="root" />
<property name="password" value="${jdbc.password}" />
</bean>
及
文件:C:/jdbc.properties
现在,我的问题是,我不知道这个文件(jdbc.properties)的确切位置,因为这个应用程序将在不同的计算机上运行,在某些地方,它安装在c:,有时可能安装在f:。。所以如果我不知道这个文件的路径,如果有,我可以找到它
谢谢是的。您可以让
Spring
在类路径中查找文件。该文件可以存在于不同机器上的不同位置,但只要它存在于类路径上,就会被加载
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>
</bean>
类路径:jdbc.properties
有多种方法可以解决这个问题
您可以将文件位置定义为系统属性,例如-Dprops.file=file:c:/1.properties
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>$props.file</value>
</property>
</bean>
谢谢,不同机器上的文件也将具有不同的凭据,但是我认为,在每种情况下,类路径中的文件都是相同的,因此,在类路径hep中放置这个文件,或者以任何其他方式,我们可以像您想要的Spring概要文件一样执行它的声音。看到这一点谢谢,如果你能对你的第二个解决方案有所了解,它看起来像我正在寻找的,但如果你能以这种方式给出占位符的小例子,它会找到文件吗,如果它在例如F:否,你必须在应用程序启动脚本中指明确切的位置,例如java-Dprops.file=file:F:/dir/1.properties-jarmain.jar但这是我的问题,我不知道文件的位置,因为不同机器的位置不同,是否有任何方法可以找到名为jdbc.properties的文件您可以扩展PropertyPlaceHolderConfigure并找到名为file.listRoots+file.ListFiles的文件谢谢,我将在哪里编写此文件的代码。listRoos+file.ListFiles以及如何更新我的xml文件中属性“location”的位置
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>$props.file</value>
</property>
</bean>
<context:property-placeholder location="${props.file}"/>
public class ScanningPropertyPlaceholderConfigurer extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer {
@Override
public void setLocation(Resource location) {
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();