ciechanowiec opened a new pull request, #51:
URL: https://github.com/apache/sling-org-apache-sling-models-impl/pull/51
Java 14 introduced support for record classes, and Apache Sling 12 by
default runs with Java 17, allowing the use of records.
Although Apache Sling 12 supports record classes, the current latest version
of Apache Sling Models Implementation does not fully support injection in
relation to records. Specifically, for records, the Apache Sling Models
Implementation supports constructor injection similarly to a usual class if
there is an explicit constructor annotated with `javax.inject.Inject`:
```java
@Model(
adaptables = {Resource.class, SlingHttpServletRequest.class},
defaultInjectionStrategy = DefaultInjectionStrategy.REQUIRED
)
public record StudentModel(String name, int age) {
@Inject
public StudentModel(
@ValueMapValue(name = "name") @Default(values = "unknown")
String name, @ValueMapValue(name = "age") @Default(intValues = 0)
int age
) {
this.name = name;
this.age = age;
}
}
```
However, for records, Apache Sling Models Implementation does not support
constructor injection if there is an implicit constructor. Such a constructor
cannot be annotated with `javax.inject.Inject` and will not be picked up during
injection. Therefore, such a Sling Model will not be instantiated at all:
```java
@Model(
adaptables = {Resource.class, SlingHttpServletRequest.class},
defaultInjectionStrategy = DefaultInjectionStrategy.REQUIRED
)
public record StudentModel(
@ValueMapValue(name = "name") @Default(values = "unknown")
String name,
@ValueMapValue(name = "age") @Default(intValues = 0)
int age) {}
```
This pull request addresses the above issue by introducing support for
injection in records' implicit constructors.
Note:
1. For records, only constructor injection is supported since records cannot
have instance fields (code with such fields will not compile).
2. Apache Sling Models Implementation is currently based on Java 8 and may
also be executed in a Java 8 environment. Therefore, the records check is
introduced via dynamic loading of the `java.lang.Record` class.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]