【问题标题】:Not able to access application.yml properties in springboot component无法访问 springboot 组件中的 application.yml 属性
【发布时间】:2021-01-11 03:35:05
【问题描述】:

我有一个application.yml 文件,其中包含以下属性

NAME:
   CLASS:
     ID: ABC123456

这是我的 Spring Boot 组件类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class  ProcessMe {

@Value("${NAME.CLASS.ID}")
String StuId;

public boolean IsRightOrWrong(){
    System.out.println(StuId);
}
}

在上述组件中,System.out.println(StuId); 始终为空。当我想使用 Junit 测试类调用这个函数时。上面的代码有什么问题?

【问题讨论】:

  • 你能展示主类和这个完整的类,包括包结构吗?还有application.yml的路径
  • @Deadpool 我已经添加了包,我的 application.yml 文件位于应用程序的 resources 文件夹中

标签: java spring-boot spring-mvc yaml


【解决方案1】:

我想这个解决方案可以在构造函数中定义

@Component
@Slf4j
public class  ProcessMe {

String StuId;

@Autowired
ProcessMe(@Value("${NAME.CLASS.ID}") String StuId) {
    this.StuId = StuId;
}
public boolean IsRightOrWrong(){
    System.out.println(this.StuId);
}
}

希望有用

【讨论】:

  • 当试图执行测试用例时,得到org.mockito.exceptions.base.MockitoException: Unable to initialize @Spy annotated field 'result'.如何摆脱这个?
  • @Lara 如果可以的话,我需要查看代码来回答你这个问题
【解决方案2】:

如果您可以启动应用程序,那么我相信您的配置是正确的。我的意思是StuId 有一定的价值。

问题在于你如何测试When i am tying to call this function using Junit test class. What's wrong in the above code?

您似乎是从单元测试中调用的。然后你需要克隆 application.yaml 来测试配置文件然后你的测试容器可以读取数据,否则你必须模拟你的配置。

顺便说一句:Java 对象属性应该使用驼峰式大声笑

【讨论】:

    猜你喜欢
    • 2019-10-23
    • 2020-06-17
    • 2020-08-02
    • 2019-05-06
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多