Java code to read properties file

When developing the Spring project, I wanted to do an operation to read the properties file in the java code. After checking it, most of them are read in the following two ways.

method one:

<bean id="propertyConfigurer"  
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
      <property name="location">  
          <value>/WEB-INF/configs/aa.properties</value>  
      </property>  
</bean>  

Method Two:

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
   <property name="locations"><!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样  
        <array>  
            <value>classpath:public.properties</value>  
        </array>  
    </property>  
</bean>  

However, neither of these methods meet the requirements.

The value in the properties of method 1 can only be retrieved in the xml configuration file through the ${key} method, while the value in method 2 can only be retrieved through the annotation @Value(“#{key}”).


And my requirement is to read the key value through java code. So, I wrote the following code to read the properties file and get the value through getData.

@Component
public class PropertiesRead {
    private String Tag = "PropertiesRead";
    @Resource
    private BusinessLogger Log;
    private Properties props;
    public Properties getInstance() throws IOException{
        if(props==null){//判断是否读取过,只读一次
            loadProps();//读取文件
        }
        return props;
    }

    private void loadProps() {
        Log.log(Tag, "开始读取properties文件内容");
        InputStream in = null;
        // 根目录是编译的class的目录
       in = PropertiesRead.class.getResourceAsStream("/msgpackage.properties");
       props = new Properties();
        try {
            props.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
       Log.log(Tag, "加载properties文件内容结束");

    }
    public String getData(String key) throws IOException{
       return getInstance().getProperty(key);
    }
}

The code of the calling class is as follows:

@RestController
public class BusinessCommonController {
    ...
    @Resource
    private PropertiesRead pr ;
    ...
    public Object getform(HttpSession session,@RequestParam("functionId") String functionId) throws Exception {
        String trancode = pr.getData("trancode");//取值
        Log.log(TAG, trancode);
        ...
        ...
        return formReturn;
    }
}

msgpackage.properties

trancode=5389

The log is as follows, the properties file will be read for the first access, and the memory will be directly fetched when accessed again.

write picture description here
write picture description here
Share this first, if you have any questions, you are welcome to pay, I hope it will be useful to everyone.

Guess you like

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