@ConstructorBinding 似乎在 Spring Boot 2.5.4 中不起作用
@ConstructorBinding seems not to work in Spring Boot 2.5.4
我正在使用 Spring Boot 2.5.4 并尝试从属性初始化一个不可变 class:
@Configuration
@ConfigurationProperties("test")
public class Config {
public final String foo;
@ConstructorBinding
public Config(String foo) {
this.foo = foo;
}
}
application.yml:
test:
foo: bar
主要class:
@SpringBootApplication
@ConfigurationPropertiesScan
public class Application implements CommandLineRunner {
@Autowired Config config;
public Application(Config config) {
this.config = config;
}
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
@Override
public void run(String... args) {
System.out.println(config.foo);
}
}
我希望它能启动并打印“bar”。但是,它无法以
开头
Parameter 0 of constructor in Config required a bean of type 'java.lang.String' that could not be found.
当我删除 @ConstructorBinding
并添加一个 setter 和 nullary 构造函数时,它确实有效。
在class级添加@ConstructorBinding
。并删除 @Configuration
注释。像这样,
@ConstructorBinding
@ConfigurationProperties("test")
public class Config {
public final String foo;
public Config(String foo) {
this.foo = foo;
}
}
我正在使用 Spring Boot 2.5.4 并尝试从属性初始化一个不可变 class:
@Configuration
@ConfigurationProperties("test")
public class Config {
public final String foo;
@ConstructorBinding
public Config(String foo) {
this.foo = foo;
}
}
application.yml:
test:
foo: bar
主要class:
@SpringBootApplication
@ConfigurationPropertiesScan
public class Application implements CommandLineRunner {
@Autowired Config config;
public Application(Config config) {
this.config = config;
}
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
@Override
public void run(String... args) {
System.out.println(config.foo);
}
}
我希望它能启动并打印“bar”。但是,它无法以
开头Parameter 0 of constructor in Config required a bean of type 'java.lang.String' that could not be found.
当我删除 @ConstructorBinding
并添加一个 setter 和 nullary 构造函数时,它确实有效。
在class级添加@ConstructorBinding
。并删除 @Configuration
注释。像这样,
@ConstructorBinding
@ConfigurationProperties("test")
public class Config {
public final String foo;
public Config(String foo) {
this.foo = foo;
}
}