【问题标题】:Using @Value annotation in Spring Starter Class在 Spring Starter 类中使用 @Value 注解
【发布时间】:2015-01-30 10:08:25
【问题描述】:

我正在使用 Spring Boot 启动一个嵌入式 Tomcat,其中包含我的应用程序。此 Tomcat 服务器位于防火墙后面,对于与外界的所有连接,我需要使用带身份验证的代理。

出于这个原因,我在我的 main 方法中启动 Spring 应用程序之前配置了一个 Authenticator

使用固定的用户名/密码一切正常,但我想从属性文件中读取这些,因此我尝试通过注入这些

@Value("${proxy.user}")
private String proxyUser;
@Value("${proxy.password}")
private String proxyPassword;

但这些总是评估为null。我猜那是因为 ApplicationContext 和 Spring Application 不存在,当实例化具有 main 方法的类时......

对于这种情况有最佳做法吗?我是否只是以“老式”方式阅读属性?

类看起来像这样:

@Configuration
@EnableAutoConfiguration
public class Application {

    @Value("${proxy.user}")
    private String proxyUser;
    @Value("${proxy.password}")
    private String proxyPassword;

    public static void main(String[] args) {
        new Application().run();
    }

    private void run() {
        ProxyAuthenticator proxyAuth = new ProxyAuthenticator(proxyUser, proxyPassword);
        Authenticator.setDefault(proxyAuth);

        // Spring Context starten
        ConfigurableApplicationContext context = SpringApplication.run(Application.class);
    }
}

【问题讨论】:

  • @ConfigurationProperties 添加到您的Application 班级。
  • 由于我将属性放入 Spring 默认拾取的 application.properties 中,这应该不是必需的,不是吗?
  • 如果您将属性放在 application.properties 中,它有可能被覆盖。请参阅以下文档,其中提供了有关解析属性值的顺序的详细信息。 docs.spring.io/spring-boot/docs/current/reference/html/…
  • 我想我以前读过那个网站。在我看来,application.properties 被读取而不是被覆盖,因为 Spring 使用了其中的日志记录语句和几个特定于 DB 的属性。该网站上的 Property-Reading-Hierarchy 中的其他替代方案在此应用中均无效。
  • 能否告诉我您项目中 application.properties 文件的位置?

标签: java spring spring-boot


【解决方案1】:

问题是您的 main 您没有使用 Spring Boot,您只是在创建一个新实例。

public static void main(String[] args) {
    new Application().run();
}

现在在您的 run 方法中,您尝试使用尚未初始化的属性,因为它只是一个新实例而不是 Spring 配置的实例。

您需要在 main 方法中启动您的应用程序,然后您可以配置ProxyAuthenticator

【讨论】:

  • 之后你是什么意思,我需要在 main 中运行一些日志记录,从 application.properties 获取变量
猜你喜欢
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
相关资源
最近更新 更多