Close

Spring Framework - @PostConstruct Examples

Spring Framework 

    @PostConstruct
private void postConstruct(){
List<String> roles = Arrays.asList("admin", "real-only", "guest");
DataFactory dataFactory = new DataFactory();
for (int i = 1; i <= 10; i++) {
User user = new User();
user.setId(i);
user.setName(dataFactory.getName());
user.setRole(dataFactory.getItem(roles));
userMap.put((long) i, user);
}
}
Original Post




public class RarelyUsedBean {

@PostConstruct
private void initialize() {
System.out.println("RarelyUsedBean initializing");
}

public void doSomething() {
System.out.println("RarelyUsedBean method being called");
}
}
Original Post




import jakarta.annotation.PostConstruct;

public class AlwaysBeingUsedBean {

@PostConstruct
public void init() {
System.out.println("AlwaysBeingUsedBean initializing");
}
}
Original Post




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




See Also