我有这个代码:
配置.java:
public class Config {
int a;
String b;
float c;
long d;
// getters and setters
}
ClassB.java(此类应该读取 application.properties 并从中生成配置):
@ConfigurationProperties
@Configuration
@Component
public class ClassB {
@NestedConfigurationProperty
Config config = new Config();
@Bean
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
}
ClassA.java:
@Configuration
@Component
public class ClassA { // consumes config
Config config;
public ClassA(Config config) {
if (config == null) {
throw new NullPointerException();
}
this.config = config;
}
}
和应用程序属性:
config.a=1
config.b=foo
config.c=3.14
config.d=1234567890L
这段代码给了我以下异常:
The dependencies of some of the beans in the application context form a cycle:
classA defined in file [/Users/xxx/code/temp/spring-cycle/target/classes/com/example/demo/ClassA.class]
┌─────┐
| classB
└─────┘
为什么?我怎样才能解决这个问题?有趣的是,如果我像这样修改
application.properties
:
a=1
b=foo
c=3.14
d=1234567890L
那么也不例外,但当然在这种情况下,
config
变量不会使用application.properties
中的值进行初始化。
有人可以帮助我吗?
您也许可以使用
@Value("${<variable name in application.properties>}")
在配置类上像这样:
public class Config {
@Value("${a}")
int a;
@Value("${b}")
String b;
@Value("${c}")
float c;
@Value("${d}")
long d;
// getters and setters
}
这将直接自动初始化 .properties 文件中的变量,我认为您可能不需要 A 类、B 类。
让我知道这是否有效