I started learning Spring Boot last week, so I'm still getting the hang of everything. Autowired seems nice, but I'm occasionally having trouble with it when using it on fields, such as repositories. I've tried searching for what the requirements are for using it, but I can't really find a definitive source.
For example, and please correct any of these if they are wrong, I know:
- Don't instantiate the field yourself. Otherwise, the Autowiring won't work.
- The object can't be static, because static fields are set up before Spring is even active (there is a workaround, however).
- The class the field is in must at least have @Component, or something derived from it.
- The package with the Autowired field must be at or below the package with @SpringBootApplication (or @ComponentScan).
I had to find points 2, 3, and 4 myself. They weren't listed anywhere and I only came across them in other StackOverflow answers.
What else is there? Essentially, I have:
@Component
public class BookSearchClient {
@Autowired
private BookRepository bookRepository;
public List<Book> processBookResult(String json) {
GoogleBook googleBooks = JsonUtil.googleBookFromJson(json);
List<Book> bookList = ConversionUtil.googleBooksToSimpleBooks(googleBooks);
for (Book book : bookList) {
bookList.add(book);
if (findBook(book) == null) {
bookRepository.save(book);
}
}
return bookList;
}
private Book findBook(Book book) {
Book foundBook = bookRepository.findByIsbn13(book.getIsbn13());
if (foundBook == null) {
foundBook = bookRepository.findByIsbn10(book.getIsbn10());
}
return foundBook;
}
}
And then:
@Repository
public interface BookRepository extends CrudRepository<Book, Long> {
Book findByIsbn10(String isbn10);
Book findByIsbn13(String isbn13);
}
I am meeting all of these so far, but am still getting a null pointer exception for bookRepository. The controllers worked without me having @Repository
on the repositories, but I figured I'd add it to see if it would help (it did not). I have similar classes that also fit the pattern outlined in the list above (specifically, @RestController
s), but in this case it's not working. I know I'm missing something, I just don't know what it is.