springboot项目实现jar包外配置文件管理

PropertySource注解

// file一般为jar包外的路径,配置文件放在跟jar同级的文件夹里或者直接同级
@PropertySource(value = "file:config.properties")
// classpath一般为jar包下的路径(一般在resources目录下)
@PropertySource({"classpath:config.properties"})

示例

config.properties:



# FTP服务器地址
ftp.hostname=10.8.0.86
# FTP服务器端口号
ftp.port=21
# FTP登录帐号
ftp.username=Administrator
# FTP登录密码
ftp.password=bspacs@13386


# 监控目录
root.dir=E:/uploadfile/


# 临时文件目录:保存添加水印的文件
temp.dir=E:/watermake/


# 图片水印路径
icon.path= E://icon.png

MonitorService :

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.TimeUnit;


/**
 * @author: HMM
 * @date: 2020/8/27 9:04
 */
@Component
@ConfigurationProperties
// file一般为jar包外的路径,配置文件放在跟jar同级的文件夹里或者直接同级
 @PropertySource(value = "file:config.properties")
// classpath一般为jar包下的路径
//@PropertySource({"classpath:config.properties"})
public class MonitorService implements ApplicationListener<ContextRefreshedEvent> {
    private Logger log = LoggerFactory.getLogger(this.getClass());


    @Value("${ftp.hostname}")
    private String hostname;
    @Value("${ftp.port}")
    private int port;
    @Value("${ftp.username}")
    private String username;
    @Value("${ftp.password}")
    private String password;


    /**
     * 本地监控目录
     */
    @Value("${root.dir}")
    private String rootDir;
    /**
     * 临时文件目录
     */
    @Value("${temp.dir}")
    private String tempDir;
    /**
     * 图片水印地址
     */
    @Value("${icon.path}")
    private String iconPath;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //保证只执行一次
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {
            //需要执行的方法
            log.info("文件自动上传服务启动...");
            log.info("[监控] 本地文件目录 = {}", rootDir);
            log.info("[FTP服务器] hostname = {}; port = {}; username = {}; password = {}", hostname, port, username, password);

            try {
                // 轮询间隔 1 秒
                long interval = TimeUnit.SECONDS.toMillis(1);
                //不使用过滤器
                FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir));
                // 添加监听器
                observer.addListener(new FileAlterationListenerAdaptor() {
                    /**
                     * 文件创建执行
                     */
                    @Override
                    public void onFileCreate(File file) {
                        log.info("[新建]:" + file.getAbsolutePath());

                        String parent = file.getParent();
                        // 反斜杠"\" 转 正斜杠 "/"
                        parent = parent.replaceAll("\\\\", "/");
                        String path="";
                        if(parent.contains(rootDir)){
                            int beginIndex = rootDir.length();
                            path = parent.substring(beginIndex);
                        }
                        FtpClientUtil.uploadFileByWatermark(hostname, port, username, password, path, tempDir, iconPath, file);
                    }

                    /**
                     * 文件创建修改
                     */
                    @Override
                    public void onFileChange(File file) {
                        log.info("[修改]:" + file.getAbsolutePath());
                    }

                    /**
                     * 文件删除
                     */
                    @Override
                    public void onFileDelete(File file) {
                        log.info("[删除]:" + file.getAbsolutePath());
                    }

                    /**
                     * 目录创建
                     */
                    @Override
                    public void onDirectoryCreate(File directory) {
                        log.info("[新建]:" + directory.getAbsolutePath());
                    }

                    /**
                     * 目录修改
                     */
                    @Override
                    public void onDirectoryChange(File directory) {
                        log.info("[修改]:" + directory.getAbsolutePath());
                    }

                    /**
                     * 目录删除
                     */
                    @Override
                    public void onDirectoryDelete(File directory) {
                        log.info("[删除]:" + directory.getAbsolutePath());
                    }

                    @Override
                    public void onStart(FileAlterationObserver observer) {
                        // TODO Auto-generated method stub
                        super.onStart(observer);
                    }

                    @Override
                    public void onStop(FileAlterationObserver observer) {
                        // TODO Auto-generated method stub
                        super.onStop(observer);
                    }

                });
                //创建文件变化监听器
                FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
                // 开始监控
                monitor.start();

            } catch (Exception e) {
                log.info("[onApplicationEvent] 文件自动上传服务启动异常, message={}", e.getMessage());
                e.printStackTrace();
            }

        }

    }
}

部署

cmd执行 java -jar FileMonitor.jar 命令运行jar包
在这里插入图片描述

参考:
【转】springboot项目实现jar包外配置文件管理

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值