[英]How to access a value in the application.properties file in Spring Boot app with main method
I have a application.properties in my src/main/resources folder. 我的src / main / resources文件夹中有一个application.properties。 it has one property
它有一个属性
username=myname
I have a class 我有一堂课
public class A
{
@Value("${username}")
private String username;
public void printUsername()
{
System.out.println(username);
}
}
when i call printusername function in my main method as follws 当我在以下主要方法中调用printusername函数时
public static void main(String[] args)
{
A object=new A();
object.printUsername();
}
it prints null. 它输出null。 please some one can tell me what i have missed?
请有人可以告诉我我错过了什么?
The @Value
annotation, as @Autowired
, works only if your class is instantiated by Spring IoC container. @Value
注释(如@Autowired
)仅在您的类由Spring IoC容器实例化时起作用。
Try to annotate your class with @Component
annotation: 尝试使用
@Component
注释对您的类进行注释:
@Component
public class A
{
@Value("${username}")
private String username;
public void printUsername()
{
System.out.println(username);
}
}
Then in your runnable class: 然后在您的可运行类中:
public class RunnableClass {
private static A object;
@Autowired
public void setA(A object){
RunnableClass.object = object;
}
public static void main(String[] args)
{
object.printUsername();
}
}
This way should work... 这种方式应该起作用...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.