【发布时间】:2021-05-31 00:10:16
【问题描述】:
我在自学Spring Boot应用,遇到了这个问题。奇怪的是,我只是按照教程做的,还是遇到了这个
Parameter 0 of constructor in com.example.Project1.service.PersonService required a bean of type 'com.example.Project1.dao.PersonDao' that could not be found.
我有一个控制器、2 个 DAO 文件、1 个用于模型的人员和 1 个用于服务类。
这些是我的代码:
人员控制器:
package com.example.Project1.api;
import com.example.Project1.model.Person;
import com.example.Project1.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("api/v1/person")
@RestController
public class PersonController {
private final PersonService personService;
@Autowired
public PersonController(PersonService personService){
this.personService = personService;
}
@PostMapping
public void addPerson(@RequestBody Person person){
personService.addPerson(person);
}
}
FakePersonDataAccessService
package com.example.Project1.dao;
import com.example.Project1.model.Person;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Repository("fakeDao")
public class FakePersonDataAccessService implements PersonDao {
private static List<Person> DB = new ArrayList<>();
@Override
public int insertPerson(UUID id, Person person){
DB.add(new Person(id, person.getName()));
return 1;
}
}
人道
package com.example.Project1.dao;
import com.example.Project1.model.Person;
import java.util.UUID;
public interface PersonDao {
int insertPerson(UUID id, Person person);
default int insertPerson(Person person){
UUID id = UUID.randomUUID();
return insertPerson(id, person);
}
}
人
package com.example.Project1.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.UUID;
public class Person {
private final UUID id;
private final String name;
public Person(@JsonProperty("id") UUID id, @JsonProperty("name") String name){
this.id = id;
this.name = name;
}
public UUID getId(){
return id;
}
public String getName(){
return name;
}
}
人员服务
package com.example.Project1.service;
import com.example.Project1.dao.PersonDao;
import com.example.Project1.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class PersonService {
private final PersonDao personDao;
@Autowired
public PersonService(@Qualifier("mongo") PersonDao personDao){
this.personDao = personDao;
}
public int addPerson(Person person){
return personDao.insertPerson(person);
}
}
我尝试在谷歌上搜索错误,但没有找到答案。希望有人能告诉我遇到的错误。谢谢~!
【问题讨论】:
标签: spring spring-boot spring-mvc