This article will introduce two methods of Spring reading property configuration files. Let’s take a look at the specific content.
1. Read through Spring Factory
Example:
public class PropertyConfig {private static AbstractBeanFactory beanFactory = null;private static final Map<String,String> cache = new oncurrentHashMap<>();@Inject public PropertyConfig(AbstractBeanFactory beanFactory) {this.beanFactory = beanFactory;}/** * Get the Value of the configuration file based on the key * @param key * @return */public static String getProperty(String key) {String propValue = "";if(cache.containsKey(key)){propValue = cache.get(key);} else {try {propValue = beanFactory.resolveEmbeddedValue("${" + key.trim() + "}");cache.put(key,propValue);}catch (IllegalArgumentException ex) {ex.printStackTrace();}}return propValue;}}Spring xml configuration
<bean> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/> <property name="ignoreResourceNotFound" value="true"/> <property name="locations"> <list> <value>classpath:props/${property-path}.properties</value> <value>classpath:important.properties</value> </list> </property></bean>Use in a project
String maxTimeInSecondsProp = PropertyConfig.getProperty("maxTimeInSeconds");2. Directly use the spirng program code to read the configuration file method of the project
import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;import org.springframework.core.io.support.PropertiesLoaderUtils;import org.springframework.core.io.FileSystemResource; public class Test { /** * @param args */ public static void main( String[] args ) { String configFile = "D:/test/application.properties"; //If the configuration file is in the classpath directory, you can use the ClassPathResource object//Resource resource = new ClassPathResource("/application.properties"); Resource resource = new FileSystemResource(configFile); try { Properties property = PropertiesLoaderUtils.loadProperties(resource); String driver = property.getProperty("jdbc.driver"); String url = property.getProperty("jdbc.url"); String userName = property.getProperty("jdbc.username"); String password = property.getProperty("jdbc.password"); } catch (IOException e1) { //log.error("read config file failed", e1); } }}If the configuration file is in the classpath directory, you can use the ClassPathResource object
Resource resource = new ClassPathResource("/application.properties");Summarize
The above is all about reading the sample code of property configuration file using the spring factory. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!