@Inject: Injects resource property into a class variable.
@PostConstruct: declares the function which would initialize the bean after deriving information based on business logic. The function is called after the all injections have completed.
Example:
@Model(adaptables = Resource.class)
public class ContactUsModel {
private String mailAddress;
private String phoneNumber;
@Inject
protected String title;
@Inject
protected String officeCode;
@PostConstruct
protected void init() {
// Business logic to transform injected values and assign to bean variables
// Example: Resolve mailAddress/phoneNumber applicable for the user's region, based on officeCode
In the above example, ‘adaptables = Resource.class’ maps the sling model against a Sling Resource.
The @Inject would inject ‘contacts’ property from the resource into ‘contacts’ class variable. The property value injection occurs after adapting the Resource into Value Map.
Optional/Required fields
@Model annotation provides ‘defaultInjectionStrategy’ attribute to indicate if the injected fields in a sling model should be required/optional.
Use ‘defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL’ to mark all injected fields as optional
Use ‘defaultInjectionStrategy = DefaultInjectionStrategy.REQUIRED’ to mark all injected fields as required. Its also the default configuration, if ‘defaultInjectionStrategy’ is not specified.
Injection strategy on Field level:
@Required / @Optional annotations can be used to selectively mark fields as required/optional.