【发布时间】: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