Good evening,
since I'm new to Java and Spring Boot, my following question might sound easy and simple to most of you, but I would like to ask what I'm doing wrong when autowiring a model - please excuse if I'm mixing terminology of java/spring boot and python/django - inside my spring boot test.
Followed some simple steps to set up a test project:
Created example project with start.spring.io
Project: Maven, Language: Java, Spring Boot 3.2.3, Java: 21
Created a small model class called Book.java and a repository called BookRepository.java
Created a placeholder test and tried to run it
Directory:
├── src
├── main
│ ├── java
│ │ ├── com.example.demo
│ │ │ ├── book
│ │ │ │ ├── models
│ │ │ │ | └── Book.java
│ │ │ │ ├── repository
│ │ │ │ │ └── BookRepository.java
│ │ │ └── DemoApplication.java
│ └── resources
├── test
│ ├── java
│ │ ├── com.example.demo
│ │ │ ├── book
│ │ │ │ ├── models
│ │ │ │ │ └── BookTest.java
├── ...
Book.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "books")
public class Book {
@Id
private String isbn;
@Column(unique = true, nullable = false)
private String title;
@Column(nullable = false)
private Integer pages;
@Column(nullable = false)
private boolean available = true;
}
BookRepository.java
public interface BookRepository extends CrudRepository<Book, String> {
}
BookTest.java
@SpringBootTest(classes = DemoApplication.class)
public class BookTest {
@Autowired private BookRepository bookRepository; // <-- works fine
@Autowired private Book book; // <-- throws error
@Test
@DisplayName("Placeholder")
public void testPlaceholder() {
System.out.println("Placeholder test get's executed!");
}
}
Now, whenever I try to autowire the book class, the following error get's thrown when running the test:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.example.demo.book.BookTest': Unsatisfied dependency expressed through field 'book': No qualifying bean of type 'com.example.demo.book.models.Book' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Might someone explain to me what I'm doing wrong or am i missing here? Obviously the error comes from my Book.java, but what and why do I have to add / change / remove something from there?
Thanks in advance and have a great sunday!