we are using SpEL to set some values to a DTO and i have grow null references set to true, and hoping SpEL has support to get and set optionals and also grow null references.

for below code snippet i get following error

java org.springframework.expression.spel.SpelEvaluationException: EL1010E: Property or field 'anotherDtoField' cannot be set on object of type 'java.util.Optional' - maybe not public or not writable?

when i try updating the optional in the sampleDto it works without any issues

    spelExpressionParser.parseExpression("#sampleDto.field1='abc'").getValue(standardEvaluationContext);

it would be nice for Spring to take care of setting and getting from optional as any other java field.

  @Test
  public void testSpel(){
    SpelExpressionParser spelExpressionParser = new SpelExpressionParser(new SpelParserConfiguration(true,true));
    StandardEvaluationContext standardEvaluationContext = new StandardEvaluationContext();
    SampleDto sampleDto = new SampleDto();
    standardEvaluationContext.setVariable("sampleDto",sampleDto);
    spelExpressionParser.parseExpression("#sampleDto.field2.anotherDtoField='abc'").getValue(standardEvaluationContext);
    assertEquals("abc", sampleDto.getField1());
  }

  class SampleDto{
    private Optional<String> field1;
    private Optional<AnotherDto> field2;
    public Optional<String> getField1() {
      return field1;
    }
    public void setField1(Optional<String> field1) {
      this.field1 = field1;
    }
    public Optional<AnotherDto> getField2() {
      return field2;
    }
    public void setField2(
        Optional<AnotherDto> field2) {
      this.field2 = field2;
    }
  }
  class AnotherDto{
    private String anotherDtoField;
    public String getAnotherDtoField() {
      return anotherDtoField;
    }
    public void setAnotherDtoField(String anotherDtoField) {
      this.anotherDtoField = anotherDtoField;
    }
  }

Comment From: quaff

Using Optional as field is not a good practice. https://stackoverflow.com/a/29033935/391148

Comment From: drekbour

Using Optional as field is not a good practice. https://stackoverflow.com/a/29033935/391148

Agree but this feels dismissive and doesn't change a fairly valid request. Getter Optional<AnotherDto> getField2() could just as easily be computing it's return value.

The use-case that drew me here is not to auto-grow an Optional but evaluate through it like this: obj.optEnum == 'MYENUM_NAME' where Optional<MyEnum> getOptEnum(). The rules on absent etc are fairly self evident.

I think users just want native handling for Optional as they have for Collection. Links to https://github.com/spring-projects/spring-framework/issues/20433

Comment From: snicoll

Let's close this one in favor of #20433. It looks like we can look at this particular use case if we consider adding support for Optional at all.