Spring读取properties配置和java原生对比

1.Spring读取properties配置

@Component
@Configurable
@EnableScheduling
@PropertySource({"classpath:config/camera.properties"})
public class BackgroundTaskService {
    @Value("${camera1.saveInterval}")
    private int saveInterval;

	// 每隔指定毫秒运行一次,上一次必须先完成
    @Scheduled(fixedDelayString = "${camera1.saveInterval}")
    public void reportCurrentTime(){}
}

2.java原生获取配置文件信息

package com.kenick.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * Created by kenick on 2018/11/14.
 */
public class PropertiesUtil {
    private final static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
    private Properties props;
    private String projectPath;

    public PropertiesUtil(){
        projectPath =  new File(this.getClass().getResource("/").getPath()).getPath();
    }

    public void loadProperties(String filePath){
        props = new Properties();
        try {
            InputStream is = new FileInputStream(filePath);
            props.load(new InputStreamReader(is,"UTF-8"));
        } catch (IOException e) {
            logger.error("配置文件读取异常",e);
        }
    }

    public String getProperty(String key){
        return props.getProperty(key.trim()).trim();
    }

    public String getProperty(String key,String defaultValue){
        String value= props.getProperty(key.trim());
        if (value == null || "".equals(value)){
            value = defaultValue;
        }
        return value.trim();
    }

    public String getProjectPath(){
        return projectPath;
    }

    public static void main(String[] args) {
        PropertiesUtil propertiesUtil = new PropertiesUtil();
        String filePath = propertiesUtil.getProjectPath() + "/config/camera.properties";
        propertiesUtil.loadProperties(filePath);
        String ip = propertiesUtil.getProperty("camera1.ip");
        System.out.println(ip);
    }
}

3.两者区别:spring在启动时加载一次配置文件,导致后续修改配置文件,将不会再生效;原生为每次运行都从文件中获取信息,所以可以达到实时生效,不过会占用更多的IO资源。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kenick

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值