无法使用@Value批注从Spring Boot中的属性文件读取值

问题描述:

我无法通过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注解 –

你的代码中有几个问题。

  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应用程序需要在主类中启动。 –