Java Autowired issue

Viewed 190

I'm struggling with @Autowired annotation issue. I have this code as an example but in my testing class Java says that my Autowired field is null. The test passes when I use AnnotationConfigApplicationContext but doesn't work with @Autowired. When I add annotation @SpringBootTest above my test class then @Autowired field then IntelliJ says "Could not autowire. No beans of 'Library' type found". I included in my root project this particular module.

@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();
    }

}

The error:

Cannot invoke "com.spring.library.Library.saveToDb()" because "this.library" is null
java.lang.NullPointerException: Cannot invoke "com.spring.library.Library.saveToDb()" because "this.library" is null

I did not notice that when I add annotation @SpringBootTest above may tests class then all tests fail and the error occurs:

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=...) with your test

2 Answers

Annotate your test class with @SpringBootTest or @SpringJUnitConfig

Related