Spring:使用 @DepoendsOn 调整 Bean 初始化顺序


#Spring


代码示例:

└── src
    └── main
        └── java
            └── demo
                ├── Main.java
                └── bean
                    ├── Bean01.java
                    └── Bean02.java

Main.java 代码:

package demo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "demo.bean")
public class Main {

	public static void main(String[] args) {
		new AnnotationConfigApplicationContext(Main.class);
	}

}

Bean01.java 代码:

package demo.bean;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class Bean01 implements InitializingBean {

	public Bean01() {
		System.out.printf("%s construct\n", getClassName());
	}

	@PostConstruct
	public void postConstruct() {
		System.out.printf("%s @PostConstruct\n", getClassName());
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.printf("%s InitializingBean.afterPropertiesSet\n", getClassName());
	}
	private String getClassName() {
		return this.getClass().getSimpleName();
	}
}

Bean02.java 代码:

package demo.bean;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class Bean02 implements InitializingBean {

	public Bean02() {
		System.out.printf("%s construct\n", getClassName());
	}

	@PostConstruct
	public void postConstruct() {
		System.out.printf("%s @PostConstruct\n", getClassName());
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.printf("%s InitializingBean.afterPropertiesSet\n", getClassName());
	}
	private String getClassName() {
		return this.getClass().getSimpleName();
	}
}

运行 Main.java,输出如下:

Bean01 construct
Bean01 @PostConstruct
Bean01 InitializingBean.afterPropertiesSet
Bean02 construct
Bean02 @PostConstruct
Bean02 InitializingBean.afterPropertiesSet

可以看到是 Bean01 先初始化,然后 Bean02 初始化。

我们可以给 Bean01 加上注解 @DependsOn("bean02"),让 bean02 先初始化:

@Component
@DependsOn("bean02")
public class Bean01 implements InitializingBean {
    // ....

再次执行 Main.java,输出如下:

Bean02 construct
Bean02 @PostConstruct
Bean02 InitializingBean.afterPropertiesSet
Bean01 construct
Bean01 @PostConstruct
Bean01 InitializingBean.afterPropertiesSet


( 本文完 )