On Running AppConfig main method. We will get this output.
EventListenerBean initializing
EventPublisherBean initializing
event received in EventListenerBean : event published from EventPublisherBean
Now if in AppConfig , we comment out @DependsOn from eventPublisherBean() ,
we might or might not get the same output. On running main method multiple times, occasionally
we will see that EventListenerBean doesn't receive event all the time (I'm using JDK 1.8
and
Spring 4.2.3). Why occasionally? Why not always? Because
during container start up, Spring can load beans in any order. There's one way to be 100% sure of the difference of not
using
@DependsOn : use @Lazy on eventListenerBean() method:
package com.logicbig.example.app;
import com.logicbig.example.bean.EventListenerBean;
import com.logicbig.example.bean.EventPublisherBean;
import org.springframework.context.annotation.*;
@Configuration
public class AppConfig {
@Bean(initMethod = "initialize")
// @DependsOn("eventListener")
public EventPublisherBean eventPublisherBean() {
return new EventPublisherBean();
}
@Bean(name = "eventListener", initMethod = "initialize")
@Lazy
public EventListenerBean eventListenerBean() {
return new EventListenerBean();
}
public static void main(String... strings) {
new AnnotationConfigApplicationContext(AppConfig.class);
}
}
That would cause
EventListenerBean not to load during start up but when it is used by some other bean. This
time we will see that only
EventPublisherBean is initialized by the container:
EventPublisherBean initializing
Now put back @DependsOn and don't remove @Lazy as well, we will get
the output we saw first time. Even though
we are using @Lazy , eventListenerBean is still being loaded during start up because of @DependsOn referencing of EventPublisherBean .
|