Sometimes, we need to directly read the properties configuration file in Spring code, so how do we do it? Let’s take a look at the specific content below.
We all know that Spring can read the values in properties in @Value, just configure them in the configuration file
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
<bean id="propertyConfigurer"> <property name="location"> <value>classpath:config.properties</value> </property> </bean>
Then when you need to use these to get the median values of properties, you can use it like this
@Value("${sql.name}") private String sqlName;But there is a problem with this. Every time I use the value in the configuration file, I have to declare a local variable. Is there a way to directly read the values in the configuration file using code?
The answer is to rewrite PropertyPlaceholderConfigurer
public class PropertyPlaceholder extends PropertyPlaceholderConfigurer { private static Map<String,String> propertyMap; @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { 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); }}In the configuration file, use the above class instead of PropertyPlaceholderConfigurer
<bean id="propertyConfigurer"> <property name="location"> <value>classpath:config.properties</value> </property> </bean>
This way, it can be obtained directly in the code by programming
PropertyPlaceholder.getProperty("sql.name");If it is multiple configuration files, configure the locations attribute
<bean id="propertyConfigurer" > <property name="ignoreResourceNotFound" value="true"/> <property name="locations"> <list> <value>file:./jdbc.properties</value> <value>file:./module.config.properties</value> <value>classpath:jdbc.properties</value> <value>classpath*:*.config.properties</value> </list> </property> </bean>
Summarize
The above is all about Spring's code to read the parsing of properties file instances. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Spring instantiation bean process analysis and complete code examples
Spring factory method creation (instandardization) bean instance code
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!