gg ff
gg ff

Reputation: 519

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

Upvotes: 0

Views: 4920

Answers (2)

Ori Marko
Ori Marko

Reputation: 58892

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

Upvotes: 2

David Lavender
David Lavender

Reputation: 8331

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 @PostConstructs in some order

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

Upvotes: 3

Related Questions