【发布时间】:2020-03-30 12:05:49
【问题描述】:
我在此类 B 中有一个使用 new B(this); 创建的类,我想使用 application.properties 中的值。但是因为(据我所知)因为它不是用 Spring 创建的,所以它不会有任何注入(我使用 @Value 注释)
这就是类的创建方式:
@Component
public class A {
public B getB(){return new B(this);}
/**
a lot more stuff
**/
}
有问题的班级:
public class B {
private A a;
public B(A a){
this.a = a;
}
@Value("${threshold}")
private String threshold; //this is null because it's not created with Spring
public String getThreshold(){
return threshold;
}
/**
a lot more stuff
**/
}
所以我的问题如下:
1) 如何使用 application.properties 文件中的值或
2) 我如何写 B 是用 Spring 创建的?
一些背景资料:
- 我没有写初始代码所以我不想改变太多 但想对其进行修改,以便将来可以更好地维护
- 我没有那么多 Spring 知识,只是开始了解更多 并且更加熟悉它。
- 在第 2 点)由于构造函数以及如何通过 Spring 设置它,我正在苦苦挣扎...
任何帮助将不胜感激
【问题讨论】:
-
您可以首先将配置属性隔离到单独的 POJO 中。然后让 spring boot 将值注入 POJO。您可以使用 @Autowire 来创建该配置 POJO 的实例,无论您希望在哪里使用这些值。如果您需要,我会发布一个示例。
-
不胜感激,我想我知道你的意思,但不完全确定。
-
好的。我会为你发布一个示例答案。
-
既然
A是一个bean,你为什么不从中获得价值呢?public B(A a){ this.a = a; this.threshold = a.getThreshold(); } -
刚刚在
getB()方法上注释了@Bean
标签: java spring-boot javabeans properties-file