在Springboot应用程序中未从应用程序中获取值。
我使用“ http://start.spring.io”创建了一个简单的Springboot应用程序。我正在使用JDK 8和春季2.6.6。
我在Intellij打开了一个应用程序,并能够构建并运行它。我还添加了“ application.properties”作为我定义属性的资源:
application.baseurl=/responsiblityViewer/api
在我的demapplication.java中:
public class DemoApplication {
@Value("${application.baseurl}")
public static String baseUrl;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("Test Application baseUrl : " + baseUrl);
}
}
输出为null。
我还尝试使用我定义的“ application.yml”:
application:
baseurl: /responsiblityViewer/api
and andapply.baseurl”未被注射。我在这里做错了什么?
I created a simple SpringBoot application using "http://start.spring.io" Spring Initializr. I am using JDK 8 and Spring 2.6.6.
I opened an application in IntelliJ and was able to build it and run it. I also added "application.properties" as my resource where I defined a property :
application.baseurl=/responsiblityViewer/api
in my DemoApplication.java :
public class DemoApplication {
@Value("${application.baseurl}")
public static String baseUrl;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("Test Application baseUrl : " + baseUrl);
}
}
The output is NULL.
I also tried to use "application.yml" where I defined :
application:
baseurl: /responsiblityViewer/api
and still "application.baseurl" is not getting injected. What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有很多剖析。
首先,您不能将值注入静态属性。
其次,您将无法从静态主方法引用该属性,因为尚未构建Bean。
如果您在弹簧豆生命周期上阅读,它将有助于您理解这一点,该注射会在实例化后发生。
如果将变量定义更改为
并添加此方法,则可以观察此行为
There's a lot to dissect here.
First, you can't inject a value into a static property.
Second, you will not be able to reference that property from a static main method as the bean hasn't been constructed yet.
If you read up on the spring bean lifecycle it will help you to understand this, the injection occurs after instantiation.
You can observe this behavior if you change your variable definition to
and add this method