java - Java自动装配问题
问题描述
我正在努力解决@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 时可能会测试类然后所有测试都失败并发生错误:
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes =...) 与您的测试
解决方案
@SpringBootTest
用or注释你的测试类@SpringJUnitConfig
推荐阅读
- r - 比较两个独立 felm 模型中的系数
- lua - Lua警告设置非标准全局变量如何处理?
- php - 在wordpress中使用ajax发送文件图像
- intellij-idea - 从 Intellij Rust 中的类型提示插入的快捷方式?
- pyspark - 使用推荐 python3 和 pyspark 运行 pyspark 代码的区别
- javascript - 关于数组的思考
- shadermaterial - UNITY3D - Pink prefab because of BumpedDiffuse shader
- python - 亲和传播没有收敛,这个模型不会有任何聚类中心
- perl - 调用子程序外的子程序中定义的变量
- javascript - 如何在 JavaScript/Typescript 中轻松地将方括号表示法 (abc['prop']) 替换为点表示法 (abc.prop)?