Sai prateek
Sai prateek

Reputation: 11896

How to call a method present in @PostConstruct class

I have class MyModel.java and I'm constructing it using @PostConstruct.

@ConfigurationProperties(prefix = "test")
public static class MyModel extends Model {

    @PostConstruct
    private void postConstruct() {
    }
}

Now I want to call a method of Model class(contains field and getter setter) say:

сlass Model {

    ....
    //fields and getter setter

    public void testValues(){
    }
}

Now I want to call testValues() in @PostContruct .

How can I call it ?

Upvotes: 2

Views: 2748

Answers (1)

Vasu
Vasu

Reputation: 22402

As part of the Spring bean's life cycle, afterPropertiesSet() will be called after @PostConstruct method, you can look here, so you can use afterPropertiesSet() to call your testValues() as shown below:

MyModel class:

public class MyModel extends Model implements  InitializingBean {

    @PostConstruct
    private void postConstruct() {
        //set your values here
    }

    @Override
    public void afterPropertiesSet() {
        testValues();
    }
}

I have added the below notes from the link on spring bean's lifecylce:

Multiple lifecycle mechanisms configured for the same bean, with different initialization methods, are called as follows (emphasis is mine):

Methods annotated with @PostConstruct (called first)

afterPropertiesSet() as defined by the InitializingBean callback interface (called after @PostConstruct method)

custom configured init() method (called after afterPropertiesSet method)

Upvotes: 1

Related Questions