我想在spring-boot应用程序开始监视目录更改之后运行代码。

我已经尝试运行一个新线程,但@Autowired服务还没有设置在那一点。

我已经能够找到ApplicationPreparedEvent,它在@Autowired注释设置之前触发。理想情况下,我希望事件在应用程序准备好处理http请求时触发。

是否有更好的事件可以使用,或者在应用程序在spring-boot中激活后运行代码的更好方法?


当前回答

尝试这个方法,它将在应用程序上下文完全启动时运行您的代码。

 @Component
public class OnStartServer implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent arg0) {
                // EXECUTE YOUR CODE HERE 
    }
}

其他回答

在Spring Boot应用程序启动后执行代码块的最佳方法是使用PostConstruct注释。或者你也可以使用命令行运行器。

1. 使用PostConstruct注释

@Configuration
public class InitialDataConfiguration {

    @PostConstruct
    public void postConstruct() {
        System.out.println("Started after Spring boot application !");
    }

}

2. 使用命令行运行器bean

@Configuration
public class InitialDataConfiguration {

    @Bean
    CommandLineRunner runner() {
        return args -> {
            System.out.println("CommandLineRunner running in the UnsplashApplication class...");
        };
    }
}

尝试这个方法,它将在应用程序上下文完全启动时运行您的代码。

 @Component
public class OnStartServer implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent arg0) {
                // EXECUTE YOUR CODE HERE 
    }
}

为spring boot应用程序实现CommandLineRunner。 你需要实现run方法,

public classs SpringBootApplication implements CommandLineRunner{

    @Override
        public void run(String... arg0) throws Exception {
        // write your logic here 

        }
}

您可以使用ApplicationRunner扩展类,重写run()方法并在那里添加代码。

import org.springframework.boot.ApplicationRunner;

@Component
public class ServerInitializer implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        //code goes here

    }
}

其实很简单:

@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}

在1.5.1.RELEASE版本上测试