2017-02-20 80 views
1

我無法通過Spring Boot從屬性文件讀取屬性。我有一個REST服務,通過瀏覽器和郵差工作,並返回一個有效的200響應數據。無法使用@Value批註從Spring Boot中的屬性文件讀取值

但是,我無法使用@Value批註通過此Spring Boot客戶端讀取屬性並獲得以下異常。

例外:

helloWorldUrl = null 
Exception in thread "main" java.lang.IllegalArgumentException: URI must not be null 
    at org.springframework.util.Assert.notNull(Assert.java:115) 
    at org.springframework.web.util.UriComponentsBuilder.fromUriString(UriComponentsBuilder.java:189) 
    at org.springframework.web.util.DefaultUriTemplateHandler.initUriComponentsBuilder(DefaultUriTemplateHandler.java:114) 
    at org.springframework.web.util.DefaultUriTemplateHandler.expandInternal(DefaultUriTemplateHandler.java:103) 
    at org.springframework.web.util.AbstractUriTemplateHandler.expand(AbstractUriTemplateHandler.java:106) 
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:612) 
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287) 
    at com.example.HelloWorldClient.main(HelloWorldClient.java:19) 

HelloWorldClient.java

public class HelloWorldClient { 

    @Value("${rest.uri}") 
    private static String helloWorldUrl; 

    public static void main(String[] args) { 
     System.out.println("helloWorldUrl = " + helloWorldUrl); 
     String message = new RestTemplate().getForObject(helloWorldUrl, String.class); 
     System.out.println("message = " + message); 
    } 

} 

application.properties

rest.uri=http://localhost:8080/hello 
+2

是'HelloWorldClient'是一個Spring bean嗎? – Andrew

+0

這個班級沒有任何註釋,因此我想這不是。 – user2325154

+0

您的主類應該用@SpringBootApplication註解 –

回答

4

你的代碼中有幾個問題。

  1. 從你發佈的樣本看來,Spring似乎還沒有開始。主類應該在主方法中運行上下文。

    @SpringBootApplication 
    public class HelloWorldApp { 
    
        public static void main(String[] args) { 
          SpringApplication.run(HelloWorldApp.class, args); 
        } 
    
    } 
    
  2. 無法將值注入靜態字段。你應該開始將它變成一個普通的班級領域。

  3. 該類必須由Spring容器管理才能使值注入可用。如果使用默認組件掃描,則可以使用@Component註釋簡單地註釋新創建的客戶端類。

    @Component 
    public class HelloWorldClient { 
        // ... 
    } 
    

    如果你不想註釋類,你可以在你的一個配置類或主要的Spring Boot類中創建一個bean。

    @SpringBootApplication 
    public class HelloWorldApp { 
    
        // ...  
    
        @Bean 
        public HelloWorldClient helloWorldClient() { 
        return new HelloWorldClient(); 
        } 
    
    } 
    

    但是,如果您是該課程的所有者,則首選選項是可取的。無論您選擇哪種方式,目標都是讓Spring上下文知道類的存在,以便注入過程可以發生。

+1

我還補充說,Spring應用程序需要在主類中啓動。 –