2016-09-20 54 views
0

我想一個數據庫加載器添加到我的春天應用程序,但我發現了以下錯誤豆:如何創建CrudRepository接口

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [org...GameRepository] found 
for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this 
dependency. Dependency annotations: {}"}} 

我讀過有關實例存儲庫,但我也看到了幾個不需要的例子,所以我錯過了什麼?如果我啓用@EnableJpaRepositories,我需要一些配置類嗎?

//GameRepository.java 
@Repository 
public interface GameRepository extends CrudRepository<Game, Long> { 
} 
//DatabaseLoader.java 
@Component 
public class DatabaseLoader implements CommandLineRunner{ 

    private final GameRepository repository; 

    @Autowired 
    public DatabaseLoader(GameRepository repository) { 
     this.repository = repository; 
    } 

    @Override 
    public void run(String... strings) throws Exception { 
     this.repository.save(new Game("Sala 1")); 
    } 
//Application.java 
@ComponentScan 
@EnableWebMvc 
public class Application extends SpringBootServletInitializer { 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

    @Override 
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
     return application.sources(Application.class); 
    } 
} 
+1

是可以componentscan跳過庫包?它獲取參數basepackages,我認爲值得去嘗試 – HRgiger

+2

刪除'@ EnableWebMvc'。用'@ SpringBootApplication'替換'@ ComponentScan'。重新啓動應用程序。還要確保你的'Application'在一個頂層包中,以便它掃描你的所有類。否則,它可能會遺漏一些類別,並且不會對您可能需要的功能進行適當的自動檢測。 –

回答

2

您需要@EnableJpaRepositories添加到您的配置

+2

或者他可以使用'@ SpringBootApplication',默認情況下它允許在classpath中加入技術。 –