I have simple Spring Boot application:
@SpringBootApplication
@EnableConfigurationProperties(DemoApplication.User.class)
public class DemoApplication {
@Autowired
User user;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@ConfigurationProperties("user")
record User(String name, int age) {}
}
Here's application.properties:
user.name=Test
user.age=10
Everything works fine and property values from application.properties are mapped correctly. Then I added new constructor to User record:
@ConfigurationProperties("user")
record User(String name, int age) {
public User(String name) {
this(name, 0);
}
}
and immediately got an error on startup:
Caused by: java.lang.NoSuchMethodException: com.example.demo.DemoApplication$User.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3833) ~[na:na]
I assume that Spring Boot is unable to pick constructor because there are two constructors for User. But how to specify that I want to use original constructor for object creation (String name, int age) ? There is @ConstructorBinding annotation but it can't be applied to class/record.
Spring Boot: 3.4.2
I have simple Spring Boot application:
@SpringBootApplication
@EnableConfigurationProperties(DemoApplication.User.class)
public class DemoApplication {
@Autowired
User user;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@ConfigurationProperties("user")
record User(String name, int age) {}
}
Here's application.properties:
user.name=Test
user.age=10
Everything works fine and property values from application.properties are mapped correctly. Then I added new constructor to User record:
@ConfigurationProperties("user")
record User(String name, int age) {
public User(String name) {
this(name, 0);
}
}
and immediately got an error on startup:
Caused by: java.lang.NoSuchMethodException: com.example.demo.DemoApplication$User.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3833) ~[na:na]
I assume that Spring Boot is unable to pick constructor because there are two constructors for User. But how to specify that I want to use original constructor for object creation (String name, int age) ? There is @ConstructorBinding annotation but it can't be applied to class/record.
Spring Boot: 3.4.2
Share Improve this question asked Feb 17 at 22:53 SergiySergiy 2,0714 gold badges25 silver badges37 bronze badges1 Answer
Reset to default 5When adding an extra constructor to a @ConfigurationProperties
annotated record in Spring Boot, you need to explicitly tell Spring Boot which constructor to use for binding by annotating it with @ConstructorBinding
.
@ConfigurationProperties("user")
record User(String name, int age) {
@ConstructorBinding
public User { // Annotate the canonical constructor
}
public User(String name) {
this(name, 0);
}
}
@ConstructorBinding
is required when multiple constructors exist to avoid ambiguity.