Perform related operations during initialization in Spring

1 Application scenario:

In the business, some specific requirements need to be completed at the time of initialization, that is, certain fixed operations are performed at startup, such as database table creation, related configuration changes, and specified acquisition of related data, etc., this There are quite a lot of business-like scenarios, and I have encountered business in recent projects. Let me briefly summarize the various implementation methods, so that you can use them directly when you encounter related needs!

2 concrete implementation

(1) Static code block (java basis):

 As long as the static code block loads this type of bytecode file, it will inevitably execute the logic in the code block, with the highest priority

(2) Construction method (java basis):

 Class loading instantiation will execute the logic in the constructor

(3) Implement the ApplicationContextAware interface (Spring):

Implement the ApplicationContextAware interface, rewrite the setApplicationContext() method, and call this method when the Spring container is initialized. You can use this to initialize related codes. This class can obtain all objects and information in the Spring container

(4) @PostConstruct annotation annotation method (javaee):

Using the annotation provided by javaee, it will be executed when the Servlet is loaded and initialized.

(5) Implement the InitializingBean interface:

 Implement the InitializingBean interface, rewrite the afterPropertiesSet() method, as the name implies, it is executed after the bean is loaded, the same as below

(6) @Bean annotation annotation method, filling initialization parameters:

@Bean annotation annotation method, fill in the initialization parameter @Bean(initMethod = ""), and use the current method as the initialization method, as above

(7) Implement the ApplicationRunner interface:

Implement the ApplicationRunner interface and rewrite the run(ApplicationArguments args) method, which will be executed after the Spring container initialization is completed, the same as below

(8) Implement the CommandLineRunner interface:

Implement the CommandLineRunner interface to rewrite the run(String... args) method, which will be executed after Spring's container initialization is completed, as above

(9) In the startup class method of SpringBoot:

SpringBoot's startup class can perform related initialization operations (just try)

(10) Monitor the ApplicationEvent event:

Monitoring the ApplicationEvent event will inevitably trigger the event after the Spring container is started, but the event will be triggered multiple times, and some operations that only need to be performed once are not advisable to use (see requirements)

Brief summary : For certain operations that only need to be performed once for the entire service, it is recommended to use 7, 8, 9, for a single bean, the rest of the points can be modified

Various implementations (9 is not written):

@Service
@Slf4j
public class InitServiceDemo implements
        InitializingBean,
        ApplicationContextAware,
        ApplicationRunner,
        CommandLineRunner {
    /**
     * 最最先执行,字节码加载立刻执行,最最优先
     */
    static {
        log.info("静态代码块初始化");
    }

    /**
     * 构造方法,只要加载bean后实例化时候立刻执行
     */
    public InitServiceDemo() {
        log.info("构造方法初始化");
    }

    @PostConstruct
    public void postConstruct() {
        log.info("postConstruct初始化");
    }

    /**
     * bean注入ioc容器时候会自动执行,同下
     */
    @Bean(initMethod = "")
    public void init() {
        log.info("bean init初始化");
    }

    /**
     * 当前bean进行初始化的时候会自动执行,同上
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("InitializingBean初始化");
    }

    /**
     * 启动即执行
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("ApplicationRunner初始化");

    }

    /**
     * 启动即执行
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        log.info("CommandLineRunner初始化");
    }

    /**

     * Spring容器初始化的时候会自动填充上下文对象,这个方法会被调用,
     * 可以利用触发指定的方法执行相关的逻辑
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("ApplicationContextAware 初始化");
    }


    /**
     * 通过监听ApplicationEvent事件触发某个操作,这个方式虽然也能触发相关的操作,
     * 但是每次都会执行,对于某个只需要执行一次的操作并不可取,
     *
     * @param event 只要启动本事件一定会触发
     */
    @EventListener
    public void listeningInit(ApplicationEvent event) {
        log.info("监听ApplicationEvent 进行相关的初始化");
    }

}

 Priority order (for reference only):

Is there anyone who likes bears, wants to travel to Gou Xiong Ling, and form a team

Guess you like

Origin blog.csdn.net/weixin_45874214/article/details/126200753