Anastasios Vlasopoulos
Anastasios Vlasopoulos

Reputation: 1802

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?

Upvotes: 1

Views: 3093

Answers (2)

Tunaki
Tunaki

Reputation: 137289

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();
        }
    
    }
    

Upvotes: 3

Grim
Grim

Reputation: 2040

The @Inject on a Field will autowire after the constructor has been called.

Note: In some Spring-Apps the @Inject may not work, use @Autowire instead.

Upvotes: 1

Related Questions