为什么@Values在SpringBoot中不给出数据?

问题描述 投票:0回答:1

我试图在SpringBoot中使用

@Value
作为我的一些字符串,当我将
@Value
设置为
string
时,没有得到任何数据,我不知道是否必须制作一个主要配置或者我忘记的东西。

@Component
public class BDController {
    @Value("${bbdd_ip}")
    private String bbdd_ip;

我得到的错误:

无法调用“java.sql.Connection.close()”,因为“c”为空

我一直在尝试连接到我的数据库,但我无法连接,因为我无法获取数据,我将其存储在

application.properties
中。

java spring-boot
1个回答
0
投票

编写尽可能多的测试。如果“c”为空,请找到使用“c”的地方并编写期望“c”不为空的测试。该测试将失败,但当您修复代码时,测试将通过。如果您怀疑 bbdd_ip 为空,请为其编写测试。我给你举个例子:

package example.feature.value;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest // run test as spring boot application, so we cal=n use autowire
class ValueTest {

    @Autowired
    BDController bdController; // obtain your bean from spring context

    @Test
    void testValue() {
        // verify you got a value defined in application.yml
        assertEquals("127.0.0.1", bdController.bbdd_ip);
    }

}

假设在application.yml中

bbdd_ip: 127.0.0.1

将所有字段设置为“包私有”也是非常舒服的。因此,如果您将测试放在同一个包中,则所有字段都将可访问。但这取决于您所写的内容以及团队的同意。对于这个测试,我在 BDCOntroller

中设置
    @Value("${bbdd_ip}")
    String bbdd_ip;

没有“private”,所以我们可以在测试中访问该字段

© www.soinside.com 2019 - 2024. All rights reserved.