我正在尝试从 Spring Boot 中的 application.properties 文件中提取数据
application.properties
host=localhost:8080
accountNumber=1234567890
TestController.java
@RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
private TestService testServiceImpl;
@Value("${host}")
private String host;
@RequestMapping("/test")
public String test() {
testServiceImpl = new TestService();
return testServiceImpl.getValue();
}
TestServiceImpl.java
@Service
public class TestServiceImpl implements TestService{
@Value("${accountNumber}")
public String value;
public String getValue(){
return value;
}
当我对 localhost:8080/test 进行 REST 调用时,我得到一个空值。
TestServiceImpl
已实例化,但 @Value
似乎不起作用。
我错过了什么吗?
解决方案:
我所要做的就是删除行 testServiceImpl = new TestService();
我假设它这样做是因为 new TestService()
正在覆盖 TestService
最佳答案
更新:
Spring的DI是通过@Autowired注解实现的,它为我们创建了对象。
@Autowired
private TestService testServiceImpl;
.
.
.
@RequestMapping("/test")
public String test() {
// testServiceImpl = new TestService(); // make comment this line
return testServiceImpl.getValue();
}
关于java - 在 Spring Boot 中通过 @Value 检索 application.properties 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44298330/