在Springboot应用程序中未从应用程序中获取值。

发布于 2025-01-22 20:29:02 字数 750 浏览 2 评论 0原文

我使用“ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2025-01-29 20:29:02

这里有很多剖析。

首先,您不能将值注入静态属性。

其次,您将无法从静态主方法引用该属性,因为尚未构建Bean。

如果您在弹簧豆生命周期上阅读,它将有助于您理解这一点,该注射会在实例化后发生。

如果将变量定义更改为

public String baseUrl;

并添加此方法,则可以观察此行为

@PostConstruct
public void printIt() {
  log.debug(baseUrl);
}

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

public String baseUrl;

and add this method

@PostConstruct
public void printIt() {
  log.debug(baseUrl);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文