繁体   English   中英

无法访问 springboot 组件中的 application.yml 属性

[英]Not able to access application.yml properties in springboot component

我有一个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 测试类调用这个函数时。 上面的代码有什么问题?

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

@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);
}
}

希望有用

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

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

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

顺便说一句:Java 对象属性应该使用驼峰式大小写 lol

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM