Search code examples
springconstructordependency-injectionmanaged-bean

Injecting a bean inside another bean and use it in the constructor?


I have a bean that looks like this:

@Component
@Scope("session")
public class AlarmChartSettingsBean implements Serializable {
...

Inside this bean i inject another bean like this:

@Inject
private SessionInfoBean sessionInfoBean;

Then i call the injected bean inside the constructor of the first bean like this:

public AlarmChartSettingsBean() {

    String atcaIp = sessionInfoBean.getNwConfigBean().getAtcaIP();
}

The problem is that the injected bean is null. So the question is when is that bean injected? Can i use it inside the constructor or i should use it after the bean has been constructed?


Solution

  • The constructor of a Spring bean is called before Spring has any chance to autowire any fields. This explains why sessionInfoBean is null inside the constructor.

    If you want to initialize a Spring bean, you can:

    • annotate a method with @PostConstruct:

      @PostConstruct
      public void init() {
          String atcaIp = sessionInfoBean.getNwConfigBean().getAtcaIP();
      }
      
    • implement InitializingBean and write the initialization code inside the afterPropertiesSet method:

      public class AlarmChartSettingsBean implements Serializable, InitializingBean {
      
          @Override
          void afterPropertiesSet() {
              String atcaIp = sessionInfoBean.getNwConfigBean().getAtcaIP();
          }
      
      }