Spring reads the properties file

The traditional way can be configured 

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <!-- Here is the PropertiesFactoryBean class, which also has a locations property and also receives an array, the same as above -->
   <property name="locations">
       <array>
          <value>classpath:jdbc.properties</value>
       </array>
   </property>
</bean>

 Use the @Value method to read, this method needs to declare a variable every time

 

So use the following way:

Create a PropertiesUtils that inherits PropertyPlaceholderConfigurer

as follows

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class PropertiesUtils extends PropertyPlaceholderConfigurer {
	 private static Map<String,String> propertyMap;

	    @Override
	    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) {
	        super.processProperties(beanFactoryToProcess, props);
	        propertyMap = new HashMap<String, String>();
	        for (Object key : props.keySet()) {
	            String keyStr = key.toString();
	            String value = props.getProperty(keyStr);
	            propertyMap.put(keyStr, value);
	        }
	    }

	    //static method for accessing context properties
	    public static Object getProperty(String name) {
	        return propertyMap.get(name);
	    }
}	

 

Configure in spring as follows:

<!-- Read properties file -->
    <bean id="proptiesConfig" class="com.campus.utils.PropertiesUtils">  
	    <property name="locations">  
	        <array>  
	            <value>classpath:resource.properties</value> <!-- can be multiple files-->
	            <!-- <value>classpath:resource2.properties</value> -->  
	        </array>  
	    </property>  
	</bean>  

 

Then in java you can access it as follows

String value= (String) PropertiesUtils.getProperty("upload.photo"); //这里的 upload.photo
// is the key in the properties file


For example, the properties file is as follows:

aaa=D:\\TestM\\photo
bbbb=D:\\TestM\\video

则String value= (String) PropertiesUtils.getProperty("aaa");
Get the value as D:\\TestM\\photo

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326148858&siteId=291194637