Java get the value of the configuration file process parsing

This article mainly introduces the value parsing process of Java to obtain the configuration file. It is introduced in great detail through the example code, which has a certain reference value for everyone's study or work. Friends in need can refer to it

There are many system constants in large Java projects, such as database account and password, and various token values, which need unified management. If scattered into specific codes such as various classes, it will be a disaster in later management. All these variables need unified management, which are generally put into web service In the properties file, the location of the file in the project is as follows:

web-service. The contents in the properties file are as follows:

So how to get the web service What about the values in the properties file?

1. Spring's propertyplaceholderconfigurer needs to be configured in the configuration file. The specific format is as follows:

  <bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
         <value>classpath:conf/web-service.properties</value>
      </list>
    </property>
  </bean> 

2. Write a general class

  import java.io.IOException;
  import java.io.InputStream;
  import java.util.Properties;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;

  public class PropUtils {
    private static Logger logger = LoggerFactory.getLogger(PropUtils.class);
    private static Properties properties;
    static {
      InputStream in = null;
      try {
        properties = new Properties();
        in = PropUtils.class.getResourceAsStream("/conf/web-service.properties");
        properties.load(in);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    public static String getProp(String key){
      return properties.getProperty(key);
    }
  }

3. Call the general class

String maxWait = PropUtils.getProp("maxWait_2");

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>