Reputation: 57
I'm new to making APIs and Spring in general.
I'm trying to use CommandLineRunner in order to populate my repository but it says that it cannot find the required bean that I put in the parameter.
@SpringBootApplication
public class DemoApplication {
private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner initializeDB(StudentRepository studentRepository){
return (args)->{
studentRepository.save(new Student("John1", "Doe1", "asdasda1","Comp Sci1",21));
studentRepository.save(new Student("John2", "Doe2", "asdasda2","Comp Sci2",22));
studentRepository.save(new Student("John3", "Doe3", "asdasda3","Comp Sci3",23));
studentRepository.save(new Student("John4", "Doe4", "asdasda4","Comp Sci4",24));
studentRepository.save(new Student("John5", "Doe5", "asdasda5","Comp Sci5",25));
studentRepository.save(new Student("John6", "Doe6", "asdasda6","Comp Sci6",26));
logger.info("The sample data has been generated");
};
}
}
That is my application class and below is my repository class.
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.model.Student;
public interface StudentRepository extends JpaRepository<Student, Integer> {
}
Is there a basic thing that I am missing? Thanks in advance
Upvotes: 2
Views: 2467
Reputation: 16465
DemoApplication (or whichever class annotated with @SpringBootApplication
) should reside at the root of the package structure
That means, for any other classes for which you want spring to manage it's bean's lifecycle, move that to a (sub)package of DemoApplication.
In other words, if your DemoApplication is in a package src/main/java/com/yourorg then StudentRepository should be in a (sub)package of src/main/java/com/yourorg
Upvotes: 3
Reputation: 44515
If the application class is not in a super package as the other classes, you have to specify all packages in the SpringBootApplication
, which should be scanned (for component scanning, Spring Data repositories etc.).
@SpringBootApplication(scanBasePackages= {"package1", "package2"})
or for a typesafe approach
@SpringBootApplication(scanBasePackageClasses = {ClassFromPackage1.class, ClassFromPackage2.class})
Alternatively move all packages to a subpackage of the application class package, so that all the default mechanisms take place.
Upvotes: 2