Spring学习总结(4)-Spring生命周期的回调

参考文档:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-lifecycle

Spring官方文档是这么写的:

Multiple lifecycle mechanisms configured for the same bean, with different initialization methods, are called as follows:

  1. Methods annotated with @PostConstruct

  2. afterPropertiesSet() as defined by the InitializingBean callback interface

  3. A custom configured init() method

Destroy methods are called in the same order:

  1. Methods annotated with @PreDestroy

  2. destroy() as defined by the DisposableBean callback interface

  3. A custom configured destroy() method

1、Spring生命周期初始化阶段的回调:

1.1 在方法上使用 @PostConstruct 注解,这个方法会在类的构造方法之后执行。

1.2 继承InitializingBean接口,并实现afterPropertiesSet()方法,是接口的回调方法,页会在构造方法之后执行,但执行顺序会在@PostConstruct注解方法之后。

1.3 在类中写一个 init() 方法,但需要使用XML配置上写init-method="init",如:<bean id="**" class="***" init-method="init">

代码如下:

@Service
public class UserServiceImpl implements UserService, InitializingBean {

    //构造方法
    private UserServiceImpl(){
        System.out.println("构造方法");
    }

    // Service的方法
    public String getUser(){
        System.out.println("我是getUser");
        return "11";
    }

    @PostConstruct
    public void postConstruct(){
        System.out.println("PostConstruct");
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet");
    }

}

测试:在测试用例中调用UserServiceImpl的getUser方法,输出的结果如下:

构造方法
PostConstruct
afterPropertiesSet
我是getUser

总结:这三种方法的作用是,构造方法里不好实现的内容,都可以使用这三种方法实现,起到类初始化的加载必要内容的作用。

   推荐使用1.1的方法,方便好用。1.2的方法需要额外继承接口,对类的结构会有破坏性,不推荐使用。因现在追求零配置文件,所以不推荐使用1.3的方法,所以我也没写。

2、Spring生命周期销毁阶段的回调:

2.1 在方法上使用注解@PreDestroy

2.2 继承DisposableBean接口,并实现destroy()方法

2.3 在类中写一个 destroy() 方法,并在XML文件中的bean里配置destroy-method

销毁阶段我没写例子,大家可以自行尝试。

 
3、depends-on显示声明类的前后依赖关系
  这个使用方式表示两个类之间并没有显示的注入依赖关系,但beanOne在初始化时,需要获取manager的内容,比如公共变量等。
3.1 XML声明depends-on
<bean id="beanOne" class="ExampleBean" depends-on="manager"/>
<bean id="manager" class="ManagerBean" />

4、lazy懒加载

  @Lazy 表示在容器初始化时不加载,在真正使用时才把类初始化。

原文地址:https://www.cnblogs.com/huanshilang/p/11745510.html