DEV Community

MAYUR KUMBHAR
MAYUR KUMBHAR

Posted on

@PostContruct Annotation in Spring

Issue?

Spring beans are most basic building block of spring framework. We have seen ways we can create the beans in spring in this post and its benefits. We also understood that there is drawback of using @Component annotation for bean creation.

With @Component you can not specify or configure how the bean is created, spring framework is responsible for creating & configuring the bean. With Normal @Bean annotation developer have more control on bean creation.

Solves?

To solve the issue of having some control on created bean using @Component annotation, spring provides another annotation which is called @PostConstruct annotation inspired from the Java EE edition.

With help of @PostContruct annotation, after the bean is created developer can execute the desired code. This annotation is applied on the method of the bean class which marked as @Component.


@Component
class BeanExample {

    private String name;

    public BeanExample() {
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @PostConstruct
    public void initialize() {
        this.name = "DEFAULT_STRING";
    }

    public void printName() {
        System.out.println(this.name);
    }

}
Enter fullscreen mode Exit fullscreen mode

If we get the object after spring has created the bean of BeanExample class, we can call the printName() on the bean and verify that the DEFAULT_STRING is set as part of PostContruct code execution.

Use?

Whenever the application requires the some business logic to be applied after the specific object is created we can use this annotation to perform the action e.g. initialize with default values.

Top comments (0)