[英]Not able to access application.yml properties in springboot component
I have an application.yml
file which contains properties as below我有一个
application.yml
文件,其中包含如下属性
NAME:
CLASS:
ID: ABC123456
and here is my spring boot component class这是我的 Spring Boot 组件类
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Component
@Slf4j
public class ProcessMe {
@Value("${NAME.CLASS.ID}")
String StuId;
public boolean IsRightOrWrong(){
System.out.println(StuId);
}
}
In above componenent System.out.println(StuId);
在上面的组件
System.out.println(StuId);
is always coming as null.总是为空。 When i am tying to call this function using Junit test class.
当我想使用 Junit 测试类调用这个函数时。 What's wrong in the above code?
上面的代码有什么问题?
I suppose this solution to define in constructor like我想这个解决方案在构造函数中定义
@Component
@Slf4j
public class ProcessMe {
String StuId;
@Autowired
ProcessMe(@Value("${NAME.CLASS.ID}") String StuId) {
this.StuId = StuId;
}
public boolean IsRightOrWrong(){
System.out.println(this.StuId);
}
}
Hope useful希望有用
If you can start the application then I believe that your configuration is correct.如果您可以启动应用程序,那么我相信您的配置是正确的。 I mean that
StuId
have some value.我的意思是
StuId
有一些价值。
The problem is how you testing When i am tying to call this function using Junit test class. What's wrong in the above code?
问题是你如何测试
When i am tying to call this function using Junit test class. What's wrong in the above code?
When i am tying to call this function using Junit test class. What's wrong in the above code?
It seems that you're calling from the unit test.看来您是从单元测试中调用的。 Then you need to clone application.yaml to test profile then your test container can read data, otherwise you have to mock your configuration.
然后你需要克隆 application.yaml 来测试配置文件,然后你的测试容器可以读取数据,否则你必须模拟你的配置。
btw: Java Object property should using camel case lol顺便说一句:Java 对象属性应该使用驼峰式大小写 lol
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.