簡體   English   中英

在Spring Starter類中使用@Value批注

[英]Using @Value annotation in Spring Starter Class

我正在使用Spring Boot來啟動帶有我的應用程序的嵌入式Tomcat。 該Tomcat服務器位於防火牆后面,對於與外界的所有連接,我需要使用具有身份驗證的代理。

因此,我在主要方法中啟動Spring Application之前就配置了一個Authenticator

使用固定的用戶名/密碼,一切都可以正常工作,但我想從屬性文件中讀取這些內容,因此我嘗試通過

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

但是這些總是評估為null 我想這是因為實例化具有main方法的類時,ApplicationContext和Spring Application不存在。

對於這種情況是否有最佳實踐? 我是否僅以“老式”方式閱讀屬性?

類看起來像這樣:

@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);
    }
}

問題是您的main是您沒有使用Spring Boot,而只是創建了一個新實例。

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

現在,在您的run方法中,您嘗試使用尚未初始化的屬性,因為它只是一個新實例,而不是Spring配置的實例。

您將需要在main方法中啟動應用程序,然后可以配置ProxyAuthenticator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM