1.普通获取配置文件参数为空情况
- 这种情况大概率是该类未注册到spring上下文中,导致通过@Value获取不到参数信息,如果是工具类可以考虑在类上添加@Component或者@Service的方式将类注册到spring中,这样再次通过@value就可以获取到配置文件中的参数了
//@Service
@Component
public class FileMonitorTest {
}
2.继承监听器中获取配置文件参数为空情况
- 继承监听器中获取配置文件中的参数使用@value是不起作用的,可以考虑使用构造器的方式,将参数传递过来,这样就解决继承监听器中不能使用配置文件中参数的问题了
1.自定义的类,调用继承监听器时将参数传递到继承监听器类中
//@Service
@Component
public class FileMonitorTest {
@Value("${listen.savePath}")
public String savePath;
@Value("${listen.targetPath}")
private String targetPath;
/**
* @throws Exception
*/
public void startWork() throws Exception {
// 监控目录
// String rootDir = "D:\\2021\\";
// 轮询间隔 5 秒
long interval = TimeUnit.SECONDS.toMillis(5);
//
FileAlterationObserver observer = new FileAlterationObserver(
targetPath,
FileFilterUtils.and(
FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter(".txt")).or(FileFilterUtils.directoryFileFilter()),null);
observer.addListener(new MyFileListener(savePath));
FileAlterationMonitor monitor = new FileAlterationMonitor(interval,observer);
// 开始监控
System.out.println("开启文件监控");
monitor.start();
}
}
2.继承监听器类中通过构造器拿到上面传递的参数就可以了
public class MyFileListener extends FileAlterationListenerAdaptor {
private String savePath;
public MyFileListener(String savePath) {
super();
this.savePath = savePath;
}
}