Lius
2025-06-24 aaaeee46bf6d408e68cfddebea146bf382977ac9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package org.jeecg.modules.dnc.listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class FileMonitorBootstrap implements ApplicationRunner {
 
    private MultiPathMonitor monitor;
 
    @Autowired
    private FileMonitorConfig config;
 
    @Autowired
    private FileListener listener;
 
    @Bean
    public MultiPathMonitor fileMonitor() {
        return new MultiPathMonitor(
                config.getPaths(),
                config.getInterval(),
                listener
        );
    }
 
    @Override
    public void run(ApplicationArguments args) throws Exception {
        monitor = fileMonitor();
        monitor.start();
    }
 
    // 在应用关闭时停止监控
    @Bean
    public ServletContextInitializer stopMonitorOnShutdown() {
        return servletContext -> {
            servletContext.addListener(new javax.servlet.ServletContextListener() {
                @Override
                public void contextDestroyed(javax.servlet.ServletContextEvent sce) {
                    try {
                        if (monitor != null) {
                            monitor.stop();
                        }
                    } catch (Exception e) {
                        System.err.println("停止监控时出错: " + e.getMessage());
                    }
                }
            });
        };
    }
}