Bayani Portier
Bayani Portier

Reputation: 660

SlingModel still returning null when adapting item

I am trying to get Sling Models working.

I have a simple annotated POJO that maps to a JCR Node by convention as follows:

@Model(adaptables=Resource.class)

public class FlushRule {

@Inject

public String optingRegex;

}

I have set a String value in optingRegex.

When I try to use it:

FlushRule currentRule=rule.adaptTo(FlushRule.class);

Although the correct object is in rule, currentRule is null.

I looked in http://localhost:4502/system/console/adapters and couldn't find any adapters.

Any tips would be appreciated.

Upvotes: 0

Views: 3240

Answers (2)

Manish Paul
Manish Paul

Reputation: 183

Another reason why the Sling Model object could be null is when the Sling Model has a parameterised constructor and no default constructor.

Example:

@Model(adaptables = Resource.class)
public class CompetitionRound {

    @Inject
    String round;

    public CompetitionRound(String round) { 
        this.round = round;
    }

}

Add a default constructor and it should work.

@Model(adaptables = Resource.class)
public class CompetitionRound {

    @Inject
    String round;

    public CompetitionRound() {

    }   

    public CompetitionRound(String round) { 
        this.round = round;
    }

}

Upvotes: 0

Tomek Rękawek
Tomek Rękawek

Reputation: 9304

You need to add following lines to the maven-bundle-plugin configuration in your pom.xml:

<configuration>
  <instructions>
    <Sling-Model-Packages>
      org.apache.sling.models.it.models
    </Sling-Model-Packages>
  </instructions>
</configuration>

where org.apache.sling.models.it.models is the Java package containing your models. The configured package (and all its subpackages) will be scanned for @Models. More information can be found on the Sling website.

Upvotes: 1

Related Questions