繁体   English   中英

在SpringBoot中通过@Value检索application.properties值

[英]Retrieve application.properties values via @Value in SpringBoot

我试图从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 annotation实现。它为我们创建了对象。

@Autowired
private TestService testServiceImpl;
.
.
.

@RequestMapping("/test")
public String test() {
    // testServiceImpl = new TestService(); // make comment this line 
    return testServiceImpl.getValue();
}

我发现的解决方案非常简单。

我所要做的就是删除行testServiceImpl = new TestService();

我认为它是这样做的,因为新的TestService()覆盖了自动连接的TestService实例。

谢谢harshavmb验证我的解决方案。

希望这有助于许多新的春天:)

暂无
暂无

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

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