【问题标题】:Not able to read value from properties file in Spring Boot using @Value annotation无法使用 @Value 注释从 Spring Boot 中的属性文件中读取值
【发布时间】:2017-07-09 22:45:35
【问题描述】:

我无法通过 Spring Boot 从属性文件中读取属性。我有一个 REST 服务,它通过浏览器和 Postman 运行,并向我返回一个有效的 200 响应和数据。

但是,我无法使用 @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

【问题讨论】:

  • HelloWorldClient 是 Spring bean 吗?
  • 该类没有任何注释,因此我想它不是。
  • 你的主类应该用@SpringBootApplication注解
  • 你需要从你的 main 方法中调用 SpringApplication.run(HelloWorldClient.class, args) 来启动应用程序。

标签: java spring rest spring-mvc spring-boot


【解决方案1】:

你的代码有几个问题。

  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 上下文知道类的存在,以便可以进行注入过程。

【讨论】:

  • 我还要补充一点,spring 应用程序需要在主类中启动。
猜你喜欢
  • 2022-11-03
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 2021-09-01
  • 2018-09-01
  • 1970-01-01
相关资源
最近更新 更多