@SpringBootTest
class MyBlockChainServerApplicationTests {
@Autowired
UserProperties userProperties;
private String msg;
public MyBlockChainServerApplicationTests() {
this.msg = userProperties.getMsg();
}
@Test
void testHelloWorld(){
System.out.println(msg);
}
}
运行这个配置类会抛出异常NullPointerException
说明在调用测试类构造函数时userProperties还未装配,这是因为在Spring Boot的测试类中,构造函数的执行会先于@Autowired注解的装配。这意味着,如果你在测试类的构造函数中引用了一个通过@Autowired装配的bean,那么在构造函数执行时,这个bean可能还没有被初始化和装配,从而导致空指针异常等问题。
因此,为了避免此类问题,最好不要在构造函数中直接引用@Autowired装配的bean。相反,你可以在构造函数中使用参数来接收这些bean,并使用@Autowired注解来标注这些参数,这样Spring就可以正确地初始化并装配这些bean了。
把代码修改成这样就不会报错啦
@SpringBootTest
class MyBlockChainServerApplicationTests {
@Autowired
UserProperties userProperties;
private String msg;
public MyBlockChainServerApplicationTests(@Autowired UserProperties userProperties) {
this.msg = userProperties.getMsg();
}
@Test
void testHelloWorld(){
System.out.println(msg);
}
}