【问题标题】:Retrieve application.properties values via @Value in SpringBoot在 Spring Boot 中通过 @Value 检索 application.properties 值
【发布时间】:2017-06-01 04:00:50
【问题描述】:

我正在尝试从 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 的自动装配实例

【问题讨论】:

  • 很高兴您解决了自己的问题。欢迎您以answer 的形式发布您的答案。 SO 鼓励人们回答你自己的问题。 stackoverflow.com/help/self-answer
  • 由于您自动装配了testServiceImpl,spring 容器将为您创建 bean,而您通过使用 new TestService() 干预 spring 自己创建实例来拒绝。
  • @harshavmb 是的,你是对的。这就是我发现的问题所在。感谢您验证我的发现!
  • 很高兴听到您解决了!

标签: java spring spring-boot spring-annotations


【解决方案1】:

更新:

Spring 的 DI 通过 @Autowired 注解实现。它为我们创建了对象。

@Autowired
private TestService testServiceImpl;
.
.
.

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

【讨论】:

    【解决方案2】:

    我找到的解决方案很简单。

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

    我认为它这样做是因为 new TestService() 覆盖了自动装配的 TestService 实例。

    感谢harravmb 验证我的解决方案。

    希望这可以帮助许多新的 Spring-ers :)

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 2022-01-26
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 2018-01-07
      • 2021-11-24
      • 2021-10-25
      • 2014-11-04
      相关资源
      最近更新 更多