2017-03-31 68 views
0

在我的spring啓動應用程序中,我試圖將配置文件application.properties中的變量值注入到我的java類中,並且我得到一個空值。如何將屬性值注入到Spring Boot beans中

這裏是我的application.properties文件的配置:

[email protected] 
    myapp.password=user 

這裏就是我所說的配置項:

@Component 
public class MyClass{ 

     @Value("${myapp.username}") 
     public String username; 


     @Value("${myapp.password}") 
     public String password; 

     public static void main(String[] args) { 

      System.out.println(password); 
     } 

    } 

我希望有一個人是怎麼做處理同樣的問題,謝謝。

回答

0

您甚至不會讓Spring Boot容器啓動(初始化),因爲您正在直接在main下編寫代碼。

您應該有一個Application類,如下所示,以正確啓動Spring引導容器,請看here

​​

至於我的理解,你要執行的代碼,一旦容器被啓動,因此遵循以下步驟:

添加上述Application類,然後在你的NetClient組件類添加@Postconstruct方法&這個方法會被自動調用一次豆是準備,請參閱下面的代碼:

@Component 
public class NetClient { 

    @Value("${bigwater.api_config.url.login}") 
    public String url_login; 


    @Value("${bigwater.api_config.url.ws}") 
    public static String url_ws; 


    @Value("${bigwater.api_config.username}") 
    public String username; 


    @Value("${bigwater.api_config.password}") 
    public String password; 

    @Postconstruct 
    public void init() { 
     //place all of your main(String[] args) method code here 
    } 

    //Add authentification() method here 
} 
+0

謝謝,我會嘗試。 –

0

你可以ü SE這個例子中添加bean來你的配置是這樣的:

@Configuration 
@ComponentScan(basePackages = "youpackagebase") 
@PropertySource(value = { "classpath:application.properties" }) 
public class AppConfig { 

    /* 
    * PropertySourcesPlaceHolderConfigurer Bean only required for @Value("{}") annotations. 
    * Remove this bean if you are not using @Value annotations for injecting properties. 
    */ 
    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 

}

,並在你的bean:

@Component 
public class NetClient { 

@Value("${bigwater.api_config.url.login}") 
public String url_login; 

問候

相關問題