组件中的Spring boot access application.properties
我想在我的spring boot应用程序的application.properties中添加一个属性,并且能够访问它并在我的其他类中使用它,但是我得到了null 这是我的application.properties组件中的Spring boot access application.properties,spring,spring-boot,Spring,Spring Boot,我想在我的spring boot应用程序的application.properties中添加一个属性,并且能够访问它并在我的其他类中使用它,但是我得到了null 这是我的application.properties server.port=8052 subscribe.period=5 我的类将访问它 @Component public class SubscriptionService { @Value("${subscribe.period}") private Stri
server.port=8052
subscribe.period=5
我的类将访问它
@Component
public class SubscriptionService {
@Value("${subscribe.period}")
private String period
@Autowired
public SubscriptionService(String period) {
String time = period;
...
}
}
但这段时间似乎并没有被填充,实际上是空的。至少当我在eclipse中以maven build运行时,它显示为nill,我想它可能会在加载属性文件之前尝试访问它,如果是这样的话,我该如何处理呢?上面评论中的Deinum是正确的。我不知道为什么,因为它不同于我读过的所有其他在线示例,所以我想请他给出解释 我必须把@Value放在构造函数的参数中
@Component
public class SubscriptionService {
private String period
@Autowired
public SubscriptionService(@Value("${subscribe.period}") String period) {
String time = period;
...
}
}
然后它就工作了您是否为注释@Value导入了正确的类?应该是org.springframework.beans.factory.annotation.values,我不确定哪里出了问题,因为信息不充分。尝试自动连接
Environment
然后再尝试Environment.getRequiredProperty(“subscribe.period”)
只是为了确保属性正在加载感谢您的回复,可能我使用了错误的@Value导入,但我现在无法检查,因为我刚离开办公室,但我会在回家后检查。我确实尝试过自动连接环境,但当我在那个里设置断点时,它显示为空对象。但是,我也在应用程序的另一个组件中自动连接我的订阅服务,因此,我想知道我的其他组件是否可能在启动时首先初始化,这可能会导致我的构建失败,因为嵌套的事件顺序是错误的。但是,我确信application.properties位于正确的位置,因为我的嵌入式tomcat绑定到了服务器指定的正确端口。portWell您认为如何在这种情况下工作?在Spring有时间接触某个元素之前,您正在使用它?如果要使用它,需要将@值
放在构造函数arg上。事实上,我预计组件扫描会失败,说明它无法自动连接构造函数。。。