Spring-boot 如何在调用的方法中使用自动装配的 class 属性

Spring-boot how to use autowired class properties in called method

我的 spring-boot 应用程序中有以下 class

public class ClassA {

    @Autowired
    PropertiesClass propertiesClass;

    public Integer getMeSomeValue(Integer someParameter) {
        // uses some methods of propertiesClass
    } 
}

在这里,propertiesClass 实际上包含从 application.properties 文件中读取 属性 值的方法。我想对 getMeSomeValue 方法进行单元测试。下面给出了我的单元测试class

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MyApplication.class)
@WebIntegrationTest
public class ClassATest {

    @Test
    public void testGetMeSomeValue() {
        ClassA classA = new ClassA();
        Assert.assertSame("Received expected response", classA.getMeSomeValue(6025), 2345);
    }
}

当我 运行 单元测试时,在 getMeSomeValue 方法中调用 propertiesClass 的方法时出现空指针异常。 Spring-boot 中有什么方法可以让@Autowired 工作吗?

而不是

ClassA classA = new ClassA();

这样做...

@Autowired
ClassA classA;

这样 classA bean 将在 Spring 容器中可用。

在 ClassA 上调用新的构造函数不会注入您的有线 PropertiesClass,因为它不是 Spring 的 'made'。

改为

@Autowired
ClassA classA;

确保在 MyApplication.class 中调用 bean,这将使它们在上下文中可用,因为您没有使用组件扫描。