【问题标题】:How does spring boot @Value("${somevalue}") annotation work?spring boot @Value("${somevalue}") 注解是如何工作的?
【发布时间】:2021-03-10 06:50:44
【问题描述】:

我在 spring-boot 项目中有一些 @Value 注释。为简化起见,我有几个类:restcontroller、服务(用@Service 注释)和 pojo。
在每个类中,我都声明了一个变量,如下所示:

@Value("${somevalue}")
private String somevalueVariable
  1. 在控制器类中,值将按照 application.properties 中的定义进行填充。所以这里没问题。
  2. 在服务类中,该值显示为空。 这是我的问题,我应该如何解决它以从 application.properties 中获取价值

在 pojo 中,该值显示为 null,我认为这是预期的行为,因为 spring 不管理此类。

【问题讨论】:

标签: spring spring-boot


【解决方案1】:

试试这个:

import org.springframework.beans.factory.annotation.Value;


@Value("#{${somevalue}}")
private String somevalueVariable

【讨论】:

    【解决方案2】:

    ideally service class should have @Service anotation over it, either you missed that or this class is not scanned by spring context, so please add ComponentScan anotation for service class package over main class to scan classes uner this package -

    @SpringBootApplication
    @ComponentScan({"com.in28minutes.springboot"})
    public class Application 
    

    【讨论】:

      【解决方案3】:

      它使用 Spring 表达式语言 (SpEL):

      https://docs.spring.io/spring-integration/docs/5.3.0.RELEASE/reference/html/spel.html

      还有 2 个 @Value :org.springframework.beans.factory.annotation.Value 和 lombok.Value; 确保您使用的是正确的。

      要从属性中获取价值,试试这个:

      @Value("${systemValue}")
      private String systemValue;
      

      有关更多信息,我觉得这很有用: https://www.baeldung.com/spring-value-annotation

      【讨论】:

      • 我使用了正确的注释 - import org.springframework.beans.factory.annotation.Value;
      • 那么它在 restcontroller 类中如何工作,但在 @Service 类中却没有
      • 奇怪的是它在控制器而不是服务中的工作方式......试试这个baeldung.com/…也许
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 2015-09-29
      • 2018-03-03
      • 2018-12-18
      • 2017-01-20
      • 1970-01-01
      相关资源
      最近更新 更多