AEM with Lombok

Problem Statement:

How to avoid boilerplate code?

Requirement:

Avoid boilerplate code like getters and setters and make sling models look lot simpler.

Introduction:

You can annotate any field with @Getter and/or @Setter, to let Lombok generate the default getter/setter automatically.

A default getter simply returns the field and is named getFoo if the field is called foo (or isFoo if the field’s type is boolean). A default setter is named setFoo if the field is called foo, returns void, and takes 1 parameter of the same type as the field. It simply sets the field to this value.

The generated getter/setter method will be public unless you explicitly specify an AccessLevel, as shown in the example below. Legal access levels are PUBLIC, PROTECTED, PACKAGE, and PRIVATE.

You can also put a @Getter and/or @Setter annotation on a class. In that case, it’s as if you annotate all the non-static fields in that class with the annotation.

Use Lombok in sling model to avoid writing getters and setters and make the class look simpler and remove all the boilerplate code from the java class

Most of the time we usually create Sling models to grab resource properties and use them on sightly for representation. In other cases, we usually do some custom changes on these injected properties.

Using Lombok on the Sling model removes all the boilerplate code related to all the injected fields and increases maintainability.

Lombok @Getter and @Setter

Create LombokExample Interface:

package com.mysite.core.models;

import org.osgi.annotation.versioning.ConsumerType;

@ConsumerType
public interface LombokExample {
    default String getName() {
        throw new UnsupportedOperationException();
    }
}

Create LombokExampleImpl – Sling model

Lombok @Getter – create get method and @Setter creates set method

In Sightly call useObject.name / path / jcrTitle you will get resource properties

following class increases readability and maintainability of the model

package com.mysite.core.models.impl;

import javax.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.Default;
import org.apache.sling.models.annotations.Exporter;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.InjectionStrategy;
import org.apache.sling.models.annotations.injectorspecific.OSGiService;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
import org.apache.sling.models.factory.ModelFactory;
import com.adobe.cq.export.json.ExporterConstants;
import com.mysite.core.bean.ExampleBean;
import com.mysite.core.bean.ExampleConstBean;
import com.mysite.core.models.LombokExample;
import lombok.Getter;

@Model(adaptables = SlingHttpServletRequest.class, adapters = {
		LombokExample.class }, resourceType = WithoutLombokImpl.RESOURCE_TYPE)
@Exporter(name = ExporterConstants.SLING_MODEL_EXPORTER_NAME, extensions = ExporterConstants.SLING_MODEL_EXTENSION)
public class LombokExampleImpl implements LombokExample {
	public static final String RESOURCE_TYPE = "mysite/components/content/lombok";

	@Self
	private SlingHttpServletRequest request;

	@SlingObject
	private Resource currentResource;

	@SlingObject
	private ResourceResolver resourceResolver;

	@ValueMapValue
	@Getter
	private String name;

	@ValueMapValue(injectionStrategy = InjectionStrategy.OPTIONAL)
	@Getter
	private String path;

	@ValueMapValue(name = "jcr:title", injectionStrategy = InjectionStrategy.OPTIONAL)
	@Default(values = StringUtils.EMPTY)
	@Getter
	private String jcrTitle;

	@OSGiService
	private ModelFactory modelFactory;

	@PostConstruct
	private void init() {
	}
}

Lombok – @Data

Use @Data is sling model when you are trying to adapt the current resource or some resource result into a different sling model (which doesn’t have any OOTB slingscript variable or services like SlingHttpServletRequest, resource etc.)

package com.mysite.core.models.impl;

import com.adobe.cq.wcm.core.components.models.contentfragment.ContentFragment;
import com.drew.lang.annotations.Nullable;
import lombok.Data;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.InjectionStrategy;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;

import javax.annotation.PostConstruct;

@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
@Data
public class CFModelImpl{

    @ValueMapValue(name = ContentFragment.PN_PATH, injectionStrategy = InjectionStrategy.OPTIONAL)
    @Nullable
    private String fragmentPath;

    @ValueMapValue(name = ContentFragment.PN_ELEMENT_NAMES, injectionStrategy = InjectionStrategy.OPTIONAL)
    @Nullable
    private String[] elementNames;

    @ValueMapValue(name = ContentFragment.PN_VARIATION_NAME, injectionStrategy = InjectionStrategy.OPTIONAL)
    @Nullable
    private String variationName;

    @ValueMapValue(name = ContentFragment.PN_DISPLAY_MODE, injectionStrategy = InjectionStrategy.OPTIONAL)
    @Nullable
    private String displayMode;

    @PostConstruct
    private void initModel() {
    }
}

Call Adapt to this new class using ModelFactory(recommended for error handling) to get the injected resource properties

@PostConstruct
	private void init() {
		CFModelImpl cfModel = modelFactory.getModelFromWrappedRequest(request, currentResource, CFModelImpl.class);
		cfModel.getFragmentPath();
		cfModel.getElementNames();
	}

@Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter

In other words, @Data generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans:

  • Getters for all fields, setters for all non-final fields
  • Appropriate toString, equals and hashCode implementations that involve the fields of the class,
  • Constructor that initializes all final fields
  • All fields marked as transient will not be considered for hashCode and equals. All static fields will be skipped entirely (not considered for any of the generated methods, and no setter/getter will be made for them).

Create Example Bean with @Data annotation

package com.mysite.core.bean;

import lombok.Data;

@Data
public class ExampleBean {
    private String name;
    private String value;
}

Create an object for ExampleBean and set some values

@PostConstruct
private void init() {
    ExampleBean exampleBean = new ExampleBean();
    exampleBean.setName("Name");
    exampleBean.setValue("Kiran");
}

Create a constructor to only name field

define the field name field as final

package com.mysite.core.bean;

import lombok.Data;

@Data
public class ExampleConstBean {
    private final String name;
    private String value;
}

Create an object ExampleConstBean

In the below example you can see we are able to call the constructor for the name field

@PostConstruct
private void init() {
    ExampleConstBean exampleConstBean = new ExampleConstBean("Name");
    exampleConstBean.setValue("Kiran");
}

You can also use @allargsconstructor if you want a constructor for all the fields

if you want certain fields constructor then declare those fields as final

cons:

the parameters of these annotations (such as callSuper, includeFieldNames and exclude) cannot be set with @Data. If you need to set non-default values for any of these parameters, just add those annotations explicitly;

References:

https://projectlombok.org/features/GetterSetter

https://projectlombok.org/features/Data

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s