org.springframework.beans.factory.UnsatisfiedDependencyException: Ошибка при создании bean-компонента с именем voiceService - PullRequest
0 голосов
/ 24 мая 2018

Я новичок в Spring, пытаюсь создать весенний проект с mongodb.При его запуске я получаю следующую ошибку:

    2018-05-23 22:15:20.077  WARN 11610 --- [main] 
    ConfigServletWebServerApplicationContext : Exception encountered during 
    context initialization - cancelling refresh attempt: 
    org.springframework.beans.factory.UnsatisfiedDependencyException: Error 
    creating bean with name 'voteController': Unsatisfied dependency 
    expressed through field 'voteSvc'; nested exception is 
    org.springframework.beans.factory.UnsatisfiedDependencyException: Error 
    creating bean with name 'voteService': Unsatisfied dependency expressed 
    through field 'voteRepo'; nested exception is 
    org.springframework.beans.factory.BeanCreationException: Error creating 
    bean with name 'votesRepository': Invocation of init method failed; 
    nested exception is 
    org.springframework.data.mapping.PropertyReferenceException: No 
    property findAll found for type Vote!
    2018-05-23 22:15:20.081  INFO 11610 --- [main] 
    o.apache.catalina.core.StandardService   : Stopping service [Tomcat]

Здесь мой файл Application.java

    package com.hello;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @SpringBootApplication
    @ComponentScan("com.hello")
    public class Application implements CommandLineRunner {

    @Autowired
    private UserRepository userRepo;
    private IdeaRepository ideaRepo;
    private VotesRepository voteRepo;


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

    @Override
    public void run(String... args) throws Exception {


        }
     }

Вот мой VoteController.java

    package com.hello;

    import java.util.*;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.stereotype.*;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.*;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.boot.autoconfigure.*;

    @Controller
    @RequestMapping("/api")

    public class VoteController{

    @Autowired
    IVoteService voteSvc;

    @RequestMapping(value = "/votes", method = RequestMethod.GET)
    public List<Vote> findByIdeaId(int ideaId) 
    {
        List<Vote> votes = voteSvc.GetVotesByIdeaId(ideaId);
        return votes;
    }

    @RequestMapping(value = "/votes", method = RequestMethod.POST)
    public Vote PostByIdeaId(Vote vote) 
    {
        Vote votes = voteSvc.SaveVotesByIdeaId(vote);
        return votes;
    }

    @RequestMapping(value = "/votes", method = RequestMethod.DELETE)
    public void DeleteByIdeaId(Vote vote) 
    {
        voteSvc.DeleteVotesByIdeaId(vote);
     }
    }

Здесьis VoteService.java

package com.hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.*;
import  java.util.List;
import  java.util.*;

@Service
public class VoteService implements IVoteService {

    @Autowired
    VotesRepository voteRepo;

    public List<Vote> GetVotesByIdeaId(int ideaId)
    {
        List<Vote> votes = voteRepo.FindAll(ideaId);
        //List<Vote> votes = new ArrayList<Vote>();
        return votes;
    }

    public Vote SaveVotesByIdeaId(Vote vote) 
    {
        Vote voteIdea = voteRepo.save(vote);
        return voteIdea;
    }

    public void DeleteVotesByIdeaId(Vote vote)
    {
        voteRepo.delete(vote);
    }

}

Вот мой файл VoteRepository.java

package com.hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.*;
import  java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;

@Repository
public interface VotesRepository extends MongoRepository<Vote, String> {

    public List<Vote> FindAll(int IdeaId);

}

Вот мой интерфейс

package com.hello;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.*;

@Service
public interface IVoteService {


    public List<Vote> GetVotesByIdeaId(int ideaId);

    public Vote SaveVotesByIdeaId(Vote vote);

    public void DeleteVotesByIdeaId(Vote vote);

}

Вот мой файл gradle.build

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.1.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'idea-platform'
    version =  '0.1.0'
}

jar {
  manifest {
    attributes(
      'Main-Class': 'hello.Application'
    )
  }
}

sourceCompatibility = 1.8
targetCompatibility = 1.8 

repositories {
    mavenCentral()
}



dependencies {
   compile("org.springframework.boot:spring-boot-starter-web")
   compile("org.springframework.boot:spring-boot-starter-thymeleaf")
   compile("org.springframework.boot:spring-boot-devtools")
    compile("org.springframework.boot:spring-boot-starter-data-mongodb")
   testCompile("junit:junit")
}

Вот моя сущность

package com.hello;
import org.springframework.data.annotation.Id;


public class Vote {

    @Id
    public String id;

    public String user;
    public Integer ideaId;

    public Vote() {}


}

Я рассматривал другие подобные вопросы, но ни один из них не помог мне решить.

Ответы [ 2 ]

0 голосов
/ 25 мая 2018

Это не полное решение, но я тоже заметил эту проблему.Каждый из ваших репозиториев, вероятно, должен быть подключен автоматически, а не только первый.

У вас было:

@Autowired
private UserRepository userRepo;
private IdeaRepository ideaRepo;
private VotesRepository voteRepo;

Но я думаю, что вы хотели:

@Autowired
private UserRepository userRepo;

@Autowired
private IdeaRepository ideaRepo;

@Autowired
private VotesRepository voteRepo;
0 голосов
/ 24 мая 2018

Метод, который вы определили в своем хранилище, не соответствует подходу Spring Data Repositories.Предположим, что ideaId является свойством Vote, метод для поиска всех Vote с заданным ideaId должен выглядеть примерно так:

@Repository
public interface VotesRepository extends MongoRepository<Vote, String> {

    public List<Vote> findByIdeaId(int ideaId);

}

Посмотрите здесь для получения дополнительной информации о том, как реализовать репозитории данных Spring.

PS : В дополнение к этому попробуйте придерживаться соглашения об именах Java, чтобы начинать имена методов и параметров со строчной буквы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...