简体   繁体   中英

Why @PostConstruct causes NullPointerException?

I'm learning Spring Framework, while watching Evgeniy Borisov's lecture I came across this code:

Suppose we have two beans with circular dependency:

Second bean:

@Service
public class Two {

    @Autowired
    private One one;


    public String getWord() {
        return word;
    }

    private String word;


    @PostConstruct
    public void doSmth(){
        init();
        System.out.println("SECOND BEAN TEXT :"+one.getWord());
    }

        public void init(){
            word = "Second word";
    }
}

First bean:

@Service
public class One {
    @Autowired
    private Two two;

    public String getWord() {
        return word;
    }
    private String word;

    @PostConstruct
    public void doSmth(){
        init();
        System.out.println("FIRST BEAN TEXT :"+two.getWord());
    }

    public void init(){
        word = "First bean";
    }
} 

And start class:

public class StartTests {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext("test");
    }
}

If we execute StartTests class, we'll get this in output :

SECOND BEAN TEXT :null

FIRST BEAN TEXT :Second word

Yes, I understand that @PostConstructor executes before all proxies are involved, but I can't understand why First Bean works properly while Second Bean doesn't

This is just about execution order. One of them has to run first after all!

  1. Spring runs through all the @Autowiring (that's working fine)
  2. Spring runs through all the @PostConstruct s in some order

In yours, One 's @PostConstruct happens to run first, THEN Two 's afterwards.

If you want Bean One to initialize before Two , you can add @DependsOn

@DependsOn({"One"})
@Service
public class Two {

May be used on any class directly or indirectly annotated with Component or on methods annotated with Bean.

Although you will get null in the other log

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM