首页 > 解决方案 > Java自动装配问题

问题描述

我正在努力解决@Autowired注释问题。我以这段代码为例,但在我的测试类中,Java 说我的 Autowired 字段是null. 当我使用AnnotationConfigApplicationContext 但不适用于@Autowired. @SpringBootTest当我在我的测试类然后字段上方添加注释时, @AutowiredIntelliJ 会说“无法自动装配。没有找到‘库’类型的 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 =...) 与您的测试

标签: javaspringcontainersautowired

解决方案


@SpringBootTest用or注释你的测试类@SpringJUnitConfig


推荐阅读