【发布时间】:2021-08-06 08:03:08
【问题描述】:
我正在努力解决@Autowired 注释问题。我以这段代码为例,但在我的测试类中,Java 说我的 Autowired 字段是null。当我使用AnnotationConfigApplicationContext 时测试通过但不适用于@Autowired。当我在我的测试类上方添加注释@SpringBootTest 然后@Autowired 字段然后IntelliJ 说“无法自动装配。找不到'库'类型的bean”。我在我的根项目中包含了这个特定的模块。
@Repository
public class LibraryDbController {
public void saveData(){
System.out.println("Saving data to the database.");
}
public void loadData(){
System.out.println("Loading data from the database.");
}
}
@Service
public class Library {
private final List<String> books = new ArrayList<>();
private LibraryDbController libraryDbController;
public Library(LibraryDbController libraryDbController) {
this.libraryDbController = libraryDbController;
}
public void saveToDb(){
libraryDbController.saveData();
}
public void loadFromDb(){
libraryDbController.loadData();
}
}
@SpringBootTest
public class LibraryTestSuite {
@Autowired
private Library library; // <--- says "Could not autowire. No beans of 'Library' type found"
@Test
void testLoadFromDb(){
ApplicationContext context = new AnnotationConfigApplicationContext("com.spring");
Library test = context.getBean(Library.class);
test.loadFromDb();
}
@Test
void testSaveToDb(){
library.saveToDb();
}
}
错误:
无法调用“com.spring.library.Library.saveToDb()”,因为“this.library”为空
java.lang.NullPointerException:无法调用“com.spring.library.Library.saveToDb()”,因为“this.library”为空
我没有注意到当我在上面添加注解@SpringBootTest 时可能会测试类然后所有测试都失败并发生错误:
无法找到@SpringBootConfiguration,您需要在测试中使用@ContextConfiguration 或@SpringBootTest(classes=...) java.lang.IllegalStateException:找不到@SpringBootConfiguration,您需要在测试中使用@ContextConfiguration 或@SpringBootTest(classes=...)
【问题讨论】:
-
从
LibraryDbController中移除final修饰符 -
请在您的代码中包含这些包,并请添加
@SpringBootApplication注释类。如果您还没有,那是您的问题。
标签: java spring containers autowired