SpringBoot 启动时自动执行指定方法

在Spring Boot应用程序中,要实现在应用启动时自动执行某些代码,可以采用以下几种方式:

1. 使用@PostConstruct注解

@PostConstruct注解用于标记一个方法,该方法将在依赖注入完成后、构造方法之后自动执行。这适用于需要在对象创建后立即执行的初始化逻辑。

import javax.annotation.PostConstruct;

@Component
public class UsePostConstruct {

    @PostConstruct
    public void init() {
        // 启动时自动执行的代码
    }
}
2. 实现CommandLineRunner或ApplicationRunner接口

这两个接口都包含了一个run方法,该方法会在Spring应用上下文准备就绪后被调用。ApplicationRunner是CommandLineRunner的增强版,它提供了对命令行参数的访问能力。

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class UseCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // 启动时自动执行的代码
    }
}
3. 使用@EventListener注解

@EventListener注解可以用来监听Spring框架的事件。如果你想在Spring容器完全启动后执行某些操作,可以监听ContextRefreshedEvent。

import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class UseEventListener {

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 应用上下文初始化完毕后自动执行的代码
    }
}
4. 使用InitializingBean接口

InitializingBean接口提供了一个afterPropertiesSet方法,该方法会在所有属性设置完成后自动执行。

import org.springframework.beans.factory.InitializingBean;

public class UseInitializingBean implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        // 启动时自动执行的代码
    }
}
5. 使用ServletContextListener接口

ServletContextListener是一个在Servlet规范中定义的监听器接口,这个接口有个contextInitialized(ServletContextEvent sce)方法是在Web应用被Servlet容器(如Tomcat)加载并初始化时调用。

@Component
public class UseServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
    	// 启动时自动执行的代码
        ServletContextListener.super.contextInitialized(sce);
        
    }
}
6. 使用ApplicationContextAware接口

ApplicationContextAware是Spring框架中的一个接口,它允许Bean获取到Spring的ApplicationContext。这个接口中只有一个方法setApplicationContext(ApplicationContext applicationContext)在创建这个Bean的实例之后会自动调。

@Component
@Slf4j
public class UseApplicationContextAware implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 启动时自动执行的代码
        
    }
}
7. 使用静态代码块

在类中添加静态代码块,这样在Spring在扫描这类时候就会自动执行静态代码,从而达到代码自动运行的效果。

@Component
public class UseStatic {

    static{
        // 启动时自动执行的代码
    }
}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值