Skip to main content
Level 2
December 5, 2023
Solved

Sling Model: Post Construct v/s COnstructor

Hello 

 

I am curious about how Sling handles Sling Model. 

Say, I instantiate a Sling Model in Sightly, then a PostConstruct is called. Why not a constructor?

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
aanchal-sikka
aanchal-sikkaAccepted solution
Community Advisor
December 5, 2023

 

@aniketsi 

The @PostConstruct annotation essentially serves as an alternative to a constructor. If you were to employ a constructor in your model, you would observe that, upon its execution, the fields annotated with @Inject are still unassigned. Attempting further initialization with these fields at this point would result in a NullPointerException.

 

The entire sequence unfolds as follows:

  1. Sling generates a new instance of your model (e.g., new MyModel()).
  2. Sling populates all the dependencies you’ve declared using the @Inject annotation.
  3. Sling proceeds to invoke the method annotated with @PostConstruct.

Sling model annotations: Basics – Adobe Experience Manager Blog (techrevel.blog) (Refer to PostConstruct Annotation section)

Aanchal Sikka

1 reply

aanchal-sikka
Community Advisor
aanchal-sikkaCommunity AdvisorAccepted solution
Community Advisor
December 5, 2023

 

@aniketsi 

The @PostConstruct annotation essentially serves as an alternative to a constructor. If you were to employ a constructor in your model, you would observe that, upon its execution, the fields annotated with @Inject are still unassigned. Attempting further initialization with these fields at this point would result in a NullPointerException.

 

The entire sequence unfolds as follows:

  1. Sling generates a new instance of your model (e.g., new MyModel()).
  2. Sling populates all the dependencies you’ve declared using the @Inject annotation.
  3. Sling proceeds to invoke the method annotated with @PostConstruct.

Sling model annotations: Basics – Adobe Experience Manager Blog (techrevel.blog) (Refer to PostConstruct Annotation section)

Translate
Aanchal Sikka