Spring家族中一些很好用的接口和类

1.Spring Boot中CommandLineRunner和ApplicationRunner两个接口

在应用程序开发过程中,往往我们需要在容器启动的时候执行一些操作。Spring Boot中提供了CommandLineRunner和ApplicationRunner两个接口来实现这样的需求。

两个接口参数不同,其他大体相同,可根据实际需求选择合适的接口使用。CommandLineRunner接口中run方法的参数为String数组,ApplicationRunner中run方法的参数为ApplicationArguments。

package com.pifeng;

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

/**
 * @author pifeng
 * @date 2019/07/20 22:36
 */
@Component
public class RunService implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        //重新开启一个线程,让他单独去做我们想要做的操作,此时CommandLineRunner执行的操作和主线程是相互独立的,抛出异常并不会影响到主线程
        new Thread() {
            @Override
            public void run() {
                int i = 0;
                while (true) {
                    i++;
                    try {
                        Thread.sleep(10000);
                        System.out.println("过去了10秒钟……,i的值为:" + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //第40秒时抛出一个异常
                    if (i == 4) {
                        throw new RuntimeException();
                    }
                    continue;
                }
            }
        }.start();
    }
}

2.Spring中的InitializingBean与DisposableBean两个接口

在Spring中,InitializingBean和DisposableBean是两个标记接口,是Spring执行bean的初始化和销毁行为时的有用方法。

1.对于Bean实现 InitializingBean,它将运行 afterPropertiesSet()在所有的 bean 属性被设置之后。

2.对于 Bean 实现了DisposableBean,它将运行 destroy()在 Spring 容器释放该 bean 之后。

3.Spring中的BeanPostProcessor接口

BeanPostProcessor也称为Bean后置处理器,它是Spring中定义的接口,在Spring容器的创建过程中(具体为Bean初始化前后)会回调BeanPostProcessor中定义的两个方法。BeanPostProcessor的源码如下:

public interface BeanPostProcessor {


    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

    
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

}

其中postProcessBeforeInitialization方法会在每一个bean对象的初始化方法调用之前回调;postProcessAfterInitialization方法会在每个bean对象的初始化方法调用之后被回调。具体执行时期可以参考Spring中Bean的生命周期源码探究。

你可能感兴趣的:(#,Spring)