Expand my Community achievements bar.

SOLVED

Sling Model: Post Construct v/s COnstructor

Avatar

Level 2

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?

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

 

@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.

 

aanchalsikka_1-1701748829039.png

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

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

 

@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.

 

aanchalsikka_1-1701748829039.png

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