spring-boot icon indicating copy to clipboard operation
spring-boot copied to clipboard

Native reflection hints generated for @ConfigurationProperties when used on @Bean methods are incorrect when the properties class has a non-default constructor

Open philwebb opened this issue 2 years ago • 1 comments

See https://github.com/spring-cloud/spring-cloud-stream/issues/2640#issuecomment-1458611545. We might be missing some hint generation.

philwebb avatar Mar 07 '23 18:03 philwebb

Hints are generated but they're incorrect when the properties class has a constructor that takes one or more arguments. The generated hints are for constructor binding rather than setter-based binding. As described in the Cloud issue, this behaviour can be corrected by annotating the constructor of the properties class with @Autowired.

Here's an example:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Gh34507Application {
	
	@Bean
	@ConfigurationProperties("example")
	public ExampleProperties exampleProperties() {
		return new ExampleProperties("injected");
	}
	
	@Bean
	@ConfigurationProperties("autowired")
	public AutowiredProperties autowiredProperties() {
		return new AutowiredProperties("whatever");
	}

	public static void main(String[] args) {
		SpringApplication.run(Gh34507Application.class, args);
	}

}

class ExampleProperties {
	
	ExampleProperties(String value) {
	}

	private String one;

	public String getOne() {
		return one;
	}

	public void setOne(String one) {
		this.one = one;
	}

}

class AutowiredProperties {
	
	@Autowired
	AutowiredProperties(String value) {
	}

	private String one;

	public String getOne() {
		return one;
	}

	public void setOne(String one) {
		this.one = one;
	}

}

AOT processing of this application results in the following json:

  {
    "name": "com.example.demo.ExampleProperties",
    "methods": [
      {
        "name": "<init>",
        "parameterTypes": [
          "java.lang.String"
        ]
      }
    ]
  },
  {
    "name": "com.example.demo.AutowiredProperties",
    "methods": [
      {
        "name": "getOne",
        "parameterTypes": [ ]
      },
      {
        "name": "setOne",
        "parameterTypes": [
          "java.lang.String"
        ]
      }
    ]
  },

The hints for ExampleProperties are incorrect. Thanks to @Autowired, the hints for AutowiredProperties are correct.

wilkinsona avatar Mar 16 '23 10:03 wilkinsona

I am a new Open Source Contributor. Shall I work on this issue?

p-palanisami avatar Jun 18 '23 10:06 p-palanisami

Thanks for the offer, @p-palanisami, but I believe we've already fixed this one in #35564.

wilkinsona avatar Jun 21 '23 20:06 wilkinsona