Do not generate metadata for non-static nested class that are not initialized
Having the following configuration properties class defined:
@ConfigurationProperties("demo")
public class MyProps {
private InnerFoo innerFoo;
public class InnerFoo {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
public InnerFoo getInnerFoo() {
return innerFoo;
}
public void setInnerFoo(InnerFoo innerFoo) {
this.innerFoo = innerFoo;
}
}
Annotation processor generates the following spring-configuration-metadata.json file:
{
"groups": [
{
"name": "demo",
"type": "com.example.demo.props.MyProps",
"sourceType": "com.example.demo.props.MyProps"
},
{
"name": "demo.inner-foo",
"type": "com.example.demo.props.MyProps$InnerFoo",
"sourceType": "com.example.demo.props.MyProps",
"sourceMethod": "getInnerFoo()"
}
],
"properties": [
{
"name": "demo.inner-foo.bar",
"type": "java.lang.String",
"sourceType": "com.example.demo.props.MyProps$InnerFoo"
}
],
"hints": [],
"ignored": {
"properties": []
}
}
Defined property demo.inner-foo.bar cannot be resolved at runtime. In some cases the demo.innerFoo field being null, and in other with the following exception:
Failed to bind properties under 'demo.inner-foo' to com.example.demo.props.MyProps$InnerFoo:
Reason: org.springframework.boot.context.properties.source.InvalidConfigurationPropertyNameException: Configuration property name 'this$0' is not valid
Nested class like that are meant to be static.
I am second-guessing this should be a bug, actually. If you instantiate InnerFoo and make it final, it should behave as expected so we might be breaking others. Flagging to get more feedback.
Nested class like that are meant to be static.
Our examples use static but we don't state that it's required. Given this, I don't think we can expect them to be.
If you instantiate InnerFoo and make it final, it should behave as expected
This is indeed the case with this code:
@ConfigurationProperties("demo")
public class MyProps {
private final InnerFoo innerFoo = new InnerFoo();
public InnerFoo getInnerFoo() {
return this.innerFoo;
}
public class InnerFoo {
private String bar;
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
}
Perhaps the metadata annotation processor should ignore non-static nested classes when there's a setter for it. If there's no setter, it should generate metadata based on the assumption that the field will be initialised. We could even check the field to see if it has an initializer, if it's final, etc.
I am happy to take a look at this - can you assign this to me
Thanks, @Jidnyashah. I've assigned the issue to you.
@Jidnyashah how is it going? Do you still plan to contribute?