Close

Spring Framework - InitializingBean Examples

Spring Framework 

The bean ClientBean is implementing InitializingBean interface and overriding method afterPropertiesSet to do all sort of assertions like NPE etc. This example is purposely not setting ServiceBean dependency to demonstrate how we can check required fields.

Using InitializingBean is not recommended because it couples application code to Spring specific interface. Better use a method with Java @PostConstruct annotation which .serves the same purpose.

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class InitializingBeanExample {

@Bean(autowire = Autowire.BY_TYPE)
public ClientBean clientBean() {
return new ClientBean();
}

//remove following comment to fix java.lang.IllegalArgumentException: ServiceBean not set
//@Bean
public ServiceBean serviceBean() {
return new ServiceBean();
}

public static void main(String... strings) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
InitializingBeanExample.class);
ClientBean bean = context.getBean(ClientBean.class);
bean.doSomething();
}

private static class ClientBean implements InitializingBean {
private ServiceBean serviceBean;

public void setServiceBean(ServiceBean serviceBean) {
this.serviceBean = serviceBean;
}

public void doSomething() {
System.out.println("doing something with: " + serviceBean);
}

@Override
public void afterPropertiesSet() throws Exception {
if (serviceBean == null) {
throw new IllegalArgumentException("ServiceBean not set");
}
}
}

private static class ServiceBean {
}
}
Original Post




See Also