PropertyPlaceholderConfigurer: can I have a dynamic location value

right now i have this in my xml file:

<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> 

and

  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>file:C:/jdbc.properties</value> </property> </bean> 

Now my problem is that I do not know the exact location of this file (jdbc.properties), since this application will run on different computers, in some places it is installed in c :, sometimes it can be on f: .. So, if I do not know the path to this file, if there is anyway, I could find it.

thanks

+4
source share
4 answers

You can determine the location of the file as a system property, for example -Dprops.file = file: c: /1.properties

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>$props.file</value> </property> </bean> 

or

 <context:property-placeholder location="${props.file}"/> 

or you can scan the file system

 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)); } } 
+13
source
 PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); configurer.setLocation(new ClassPathResource("context.properties")); ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}, false); applicationContext.addBeanFactoryPostProcessor(configurer); applicationContext.refresh(); 
+2
source

Yes. You can let Spring find the file in the classpath. A file can exist in different places on different machines, but it will be loaded as long as it exists in the classpath.

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:jdbc.properties</value> </property> </bean> 
0
source

There are several ways to deal with it.

  • Put the file in the project so that you have the same relative path all the time.
  • Set the value during assembly, i.e. place the placeholder in the value tag and replace it during assembly by passing parameters. for example, if you use ant to create your assembly, you can use the expandproperties task.
0
source

All Articles