2016-07-14 60 views
1

我剛剛使用Spring Boot V1.3.5設置了一個新項目,並且在嘗試將存儲庫自動裝入到服務中時不斷收到NoSuchBeanDefinitionException異常。這很奇怪,因爲我有其他項目設置相同的方式工作正常。將NoSuchBeanDefinitionException存儲庫投入服務

我的應用程序類。

package api; 

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 

@SpringBootApplication 
public class Application { 

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

     System.out.println("-------------------"); 
     System.out.println("The API is running."); 
     System.out.println("-------------------"); 
    } 
} 

我的服務。

package api.services; 

import api.entity.Project; 
import api.repository.ProjectRepository; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 

@Service 
public class ProjectService { 

    @Autowired 
    private ProjectRepository projectRepository; 

    /** 
    * Saves a project entity into the database. 
    * 
    * @param project Project 
    * @return Project 
    */ 
    public Project save(Project project) { 

     return this.projectRepository.save(project); 
    } 
} 

我的存儲庫。現在

package api.repository; 

import api.entity.Project; 
import org.springframework.data.repository.CrudRepository; 
import org.springframework.stereotype.Repository; 

@Repository 
public interface ProjectRepository extends CrudRepository<Project, Integer> { 

    Project findByName(String name); 
} 

我的服務被自動連接到我的控制器,但春天似乎並不喜歡我出於某種原因庫。

任何人都可以看到什麼是錯的/失蹤?

感謝。

異常消息是:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private api.repository.ProjectRepository api.services.ProjectService.projectRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [api.repository.ProjectRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
+0

你有任何具體的實現你的ProjectRepository?它不能僅實例化一個接口。 – Gandalf

+0

當然,你不能實例化一個接口,但我沒有實例化它,我自動裝配它。我在不同的項目中具有相同的設置,並且工作正常。從文檔「但是這正是Spring Data JPA如此強大的原因:您不必編寫一個存儲庫接口的實現。當您運行應用程序時,Spring Data JPA即時創建實現。」 –

+0

我試着創建一個類似的示例項目,這是可用[這裏](https://github.com/vamsilp/testProjects.git),它爲我工作。請公開項目實體類,因爲我猜測中的方法簽名ProjectRepository可能不正確。 –

回答

0

嘗試@Component代替@Repository。

+0

嘗試過但仍然是同樣的問題。我認爲所有的刻板印象都是通過組件掃描獲得的,無論其類型如何? –

0

好吧,檢查其他設置相同方式的項目。首先,我注意到你已經使用了spring數據jpa,所以註釋@Repository無需接口,因爲spring boot會自動掃描它。最後,我認爲你需要看到這個與你具有相同配置的項目。 spring-boot-sample-data-jpa

+0

這是我做的第一件事。我也試過沒有@Repository註釋,問題仍然存在。謝謝,我會看看。 –

+0

如果您的軟件包不是默認的掃描包,請嘗試爲SpringBootRunner添加@EnableJpaRepositories(「您的包的dao」)。 –

+0

我已經試過了,它沒有工作。這不應該是必要的,因爲我的存儲庫包是我的api包的一部分。 –