Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.

Code Reuse With Custom Sling Model Injectors | AEM Community Blog Seeding

Avatar

Administrator

BlogImage.jpg

Code Reuse With Custom Sling Model Injectors by Perficient

Abstract

In my blog Writing Less Java Code in AEM with Sling Models, I talked about writing less code using Sling Models. I followed that up with Writing Less Java Code in AEM with Sling Models & Lombok. I talked about code generators helping in saving time by not writing redundant codes. You could say I am lazy. I like to use the tools and frameworks at my disposal.

But sometimes it is inevitable. We have to write code. I am anything if not efficient. When I write code, I like to make it as concise and simple to understand as possible. In this blog, I am going to talk about the reusability of code helping in writing less code.
Tag ID Model
As an example, I am going to revisit the Tag id model from that first blog post. In that example, the multifield items had a tag ids property named ./tags. This I injected into the model as ItemTags

@ChildResource
ItemTags getTags();
And ItemTags implemented Iterable

interface ItemTags extends Iterable {
}
@Model(adaptables = Resource.class, adapters = ItemTags.class)
final class ItemTagsImpl implements ItemTags {
private final List tags;
@Inject
public ItemTagsImpl(
@Self @Via("resourceResolver") final TagManager tagManager,
@Self final String[] ids) {
this.tags = Arrays.stream(ids)
.map(tagManager::resolve)
.filter(Objects::nonNull)
.collect(Collectors.toUnmodifiableList());
}
@Override
public Iterator iterator() {
return this.tags.iterator();
}
@Override
public void forEach(final Consumer<? super Tag> action) {
this.tags.forEach(action);
}
@Override
public Spliterator spliterator() {
return this.tags.spliterator();
}
}
The Sling Model code has the smallest amount of code possible. Yet, tags are ubiquitous in AEM. The chances that I may need to put in place another model that also needs to resolve tags are high. Let us explore some of the code reuse options we have.

Read Full Blog

Code Reuse With Custom Sling Model Injectors

Q&A

Please use this thread to ask the related questions.



Kautuk Sahni
Topics

Topics help categorize Community content and increase your ability to discover relevant content.

0 Replies