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

标签 java spring rest spring-mvc spring-boot

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

最佳答案

您的代码中有几个问题。

  1. 从您发布的示例来看,Spring 似乎还没有启动。主类应在您的主方法中运行上下文。

    @SpringBootApplication
    public class HelloWorldApp {
    
         public static void main(String[] args) {
              SpringApplication.run(HelloWorldApp.class, args);
         }
    
    }
    
  2. 无法将值注入(inject)静态字段。您应该首先将其更改为常规类字段。

  3. 该类必须由 Spring 容器管理,以便可以进行值注入(inject)。如果您使用默认组件扫描,您可以简单地使用@Component 注释来注释新创建的客户端类。

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

    如果您不想注释该类,您可以在您的配置类之一或您的主 Spring Boot 类中创建一个 bean。

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

    但是,如果您是类(class)的所有者,则第一个选项更可取。无论您选择哪种方式,目标都是让 Spring 上下文知道类的存在,以便注入(inject)过程能够发生。

关于java - 无法使用@Value注释从Spring Boot中的属性文件中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348221/

相关文章:

json - 将 $skip 与 SharePoint 2013 REST API 一起使用

java - 根据 Gradle 文件中的配置文件区分依赖关系

java - Hibernate 中的带注释的类

java - 在 Spring MVC 应用程序中从异常日志记录更改为异常处理的最简单方法是什么?

rest - Coldfusion 11 REST API 服务似乎意外停止工作

wcf - 什么是 REST Web 服务?

java - 非法状态异常 : getOutputStream() when creating oracle connection pool in glassfish

java - Wicket:从另一个面板在一个面板中提交表单

java - Maven 多模块构建中的生命周期阶段

java - 如何在 Java Annotation Processing 中获取字段的类型注释?