The bean ClientBean is defining a method annotated with @PostConstruct. This way we can do all sort of assertions like null check and even business logic related assertion. This example is purposely not setting ServiceBean dependency to demonstrate how we can check required fields.
Alternatively we can use 'initMethod' with @Bean annotation. For XML configuration, using init-method is alternative to doing the same thing.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import jakarta.annotation.PostConstruct;
@Configuration
public class PostConstructExample {
@Bean
public ClientBean clientBean (ServiceBean serviceBean) {
ClientBean clientBean = new ClientBean();
//uncomment following to get rid of IllegalArgumentException
//clientBean.setServiceBean(serviceBean);
return clientBean;
}
@Bean
public ServiceBean serviceBean () {
return new ServiceBean();
}
public static void main (String... strings) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
PostConstructExample.class);
ClientBean bean = context.getBean(ClientBean.class);
bean.doSomething();
}
public static class ClientBean {
private ServiceBean serviceBean;
@PostConstruct
public void myPostConstructMethod () throws Exception {
// we can do more validation than just checking null values here
if (serviceBean == null) {
throw new IllegalArgumentException("ServiceBean not set");
}
}
public void setServiceBean (ServiceBean serviceBean) {
this.serviceBean = serviceBean;
}
public void doSomething () {
System.out.println("doing something with: " + serviceBean);
}
}
public static class ServiceBean {
}
}
Original Post