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

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

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

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


当前回答

其实很简单:

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

在1.5.1.RELEASE版本上测试

其他回答

为Dave Syer的回答提供了一个例子,这就像一个魅力:

@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);

    @Override
    public void run(String...args) throws Exception {
        logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args));
    }
}

“Spring Boot”方式是使用CommandLineRunner。只需添加该类型的bean,就可以了。在Spring 4.1 (Boot 1.2)中,也有一个SmartInitializingBean,它在所有东西初始化后得到一个回调。还有SmartLifecycle(来自Spring 3)。

你可以使用@Component

@RequiredArgsConstructor
@Component
@Slf4j
public class BeerLoader implements CommandLineRunner {
    //declare 

    @Override
    public void run(String... args) throws Exception {
        //some code here 

    }

ApplicationReadyEvent仅在您希望执行的任务不是正确服务器操作所必需的情况下才有用。启动异步任务来监视某些内容的更改就是一个很好的例子。

然而,如果你的服务器在任务完成之前处于“未准备好”状态,那么最好实现SmartInitializingSingleton,因为你会在你的REST端口被打开和你的服务器为业务打开之前得到回调。

不要试图将@PostConstruct用于只应该发生一次的任务。当你注意到它被多次调用时,你会感到粗鲁的惊讶……

Spring引导提供了一个带有run()方法的ApplicationRunner接口,在应用程序启动时调用该方法。 但是,我们有一个ApplicationArguments类的实例,而不是传递给回调方法的原始String参数。

@Component
public class AppStartupRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //some logic here
    }
}