java - 在 Spring Boot 中通过 @Value 检索 application.properties 值

标签 java spring spring-boot spring-annotations

我正在尝试从 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

的 Autowiring 实例

最佳答案

更新:

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/

相关文章:

java - 如何在Java中将文本xTab空格的字符串 block 向右移动?

java - 无法解析 MVC View Spring MVC 3

database - 我真的需要 Postgres 中的空闲连接吗?

java - 继续接收javax.mail.Session$1 : method <init>()V not found when trying to send an email using Springboot + mvc

java - 如何使用 Java 访问 MySQL 中的特定行

java - 我在使用 JavaFX 画十字时遇到问题

spring - 如何从同一端口上的spring boot应用程序启动wiremock服务器?

java - 使用 cxf-jax rs 运行 REST

java - 类显示在自动完成中但无法导入 -IntelliJ

java - 防止用户在 Eclipse 中按住按键