Use spring factory to read the sample code of the property configuration file, springproperty
This article introduces two methods for Spring to read the property configuration file. Next, let's take a look at the specific content.
1. read data from the 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;}/*** obtain the Value * @ 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 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <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 projects
String maxTimeInSecondsProp = PropertyConfig.getProperty("maxTimeInSeconds");
2. directly use the spirng program code to read the configuration file 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");
Summary
The above is all about the sample code for reading the property configuration file using the spring factory. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!