SpringBoot简易读取属性文件与创建定时任务

属性文件:属性名不能包含下划线,不然可能会匹配不到

uploadLocalPath=D:/test/upload1
uploadRemotePath=D:/test/upload2
downloadLocalPath=D:/test/download3
downloadRemotePath=D:/test/download4

 

 

属性实体:属性文件的路径必须放在@PropertySource中,放在@ConfigurationProperties中会读取不到文件。必须通过set方法才能自动注入值。

@Component            添加为spring组件
@ConfigurationProperties    自动从文件中匹配属性值
@PropertySource(value = "config/timed.properties", encoding = "UTF-8")    根据路径读取属性文件内容
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * 功能描述:定时任务配置文件
 */
@Component
@ConfigurationProperties
@PropertySource(value = "config/timed.properties", encoding = "UTF-8")
public class TimedProp {
    private String uploadLocalPath;
    private String uploadRemotePath;
    private String downloadLocalPath;
    private String downloadRemotePath;

    public String getUploadLocalPath() {
        return uploadLocalPath;
    }

    public void setUploadLocalPath(String uploadLocalPath) {
        this.uploadLocalPath = uploadLocalPath;
    }

    public String getUploadRemotePath() {
        return uploadRemotePath;
    }

    public void setUploadRemotePath(String uploadRemotePath) {
        this.uploadRemotePath = uploadRemotePath;
    }

    public String getDownloadLocalPath() {
        return downloadLocalPath;
    }

    public void setDownloadLocalPath(String downloadLocalPath) {
        this.downloadLocalPath = downloadLocalPath;
    }

    public String getDownloadRemotePath() {
        return downloadRemotePath;
    }

    public void setDownloadRemotePath(String downloadRemotePath) {
        this.downloadRemotePath = downloadRemotePath;
    }
}

 

 

定时任务

@EnableScheduling  启动定时注解

@Scheduled      开始定时任务
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@EnableScheduling
public class TimedTask {
    @Resource
    private TimedProp timedProp;

    @Scheduled(cron = "0/1 5 16 * * *")  //从16点5分0秒开始,每隔1秒执行一次,直到最后一秒
    public void test() {
        System.out.println(new Date());
        System.out.println(timedProp.getUploadLocalPath());
        System.out.println(timedProp.getUploadRemotePath());
    }
}

 

@ConfigurationProperties
posted @ 2021-01-06 18:14  缀满繁星的夜空  阅读(206)  评论(0)    收藏  举报