I am having an issue with the javax.annotation.PostConstruct annotation in my Sling model.
My html file that uses my model:
<div data-sly-use="com.company.platform.component.general.textblockvalidator.TextBlockValidatorModel" data-sly-unwrap />
Model:
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
@Model(adaptables = org.apache.sling.api.resource.Resource.class)
public class TextBlockValidatorModel {
@PostConstruct
private void init() {
System.out.println();
}
public String getValidate(){
return "This works";
}
}
I can call the getter from my sightly file but I never seem to enter my @PostConstruct init() method.
IntelliJ does give me a warning on the annotation but I am not sure what I am doing wrong:
Sling-model-packages:
<Sling-Model-Packages>
...
com.asadventure.platform.component
...
</Sling-Model-Packages>
Any ideas? Thanks in advance!
First, check your Sling Model has been registered correctly by looking for your class in this web page: http://localhost:4502/system/console/status-adapters
If it isn't listed there, you most likely have not specified the <Sling-Model-Packages>
property of the maven-bundle-plugin
.
I would also try changing the access modifier for the init
method to protected
or public
.
UPDATE:
I've created a sample project for AEM 6.1 demonstrating the use of the @PostConstruct annotation.
The Sling Model class:
@Model(adaptables = Resource.class)
public class SampleModel {
private boolean postContructCalled = false;
@PostConstruct
public void init() {
this.postContructCalled = true;
}
public boolean isPostContructCalled() {
return this.postContructCalled;
}
}
And a simple HTL component:
<sly data-sly-use.model="com.github.mickleroy.models.SampleModel">
<p>@PostConstruct was called: ${model.postContructCalled}</p>
</sly>
Please take note of the use of the data-sly-use
directive - you need to provide a model name.
Also, as I mentioned in the comments, you should not be adding javax.annotation-api
as a dependency as it is part of the JDK.
Full source available here: https://github.com/mickleroy/sling-models-sample