提问者:小点点

考虑在配置中定义“package”类型的bean


我试图在Spring Boot中创建一个简单的REST服务。在我使用CrudRepository之前,一切都很好。现在我得到了这个错误-

***应用程序启动失败

描述:

公司中的现场er。Spring靴。io。受雇者EmployeeService需要“company”类型的bean。Spring靴。io。受雇者找不到EmployeeRepo“”。

措施:

考虑定义一个“company”类型的bean。Spring靴。io。受雇者“EmployeeRepo”在您的配置中***

这是我的密码-

控制者-

@RestController
public class EmployeeController {


@Autowired
EmployeeService employeeService;

@GetMapping("/employees")
public List<Employee> getAllEmployees(){
    return employeeService.getAllEmployees();
}
@GetMapping("/employees/{id}")
public Employee getEmployee(@PathVariable int id) {
    return employeeService.getEmployee(id);
}

@PostMapping("/employees")
public String addEmployee(@RequestBody Employee e) {
    employeeService.addEmployee(e );
    return "Employee Records were added successfully";
}

@PutMapping("/employees/{id}")
public String updateEmployee(@RequestBody Employee e, @PathVariable int id) {
    return employeeService.updateEmployee(e, id);
    }

@DeleteMapping("/employees/{id}")
public @ResponseBody String deleteEmployee(@PathVariable int id) {
    return employeeService.deleteEmployee(id);

}

}

服务-

@Autowired
EmployeeRepo er;

public List<Employee> getAllEmployees() {


    List<Employee> list= new ArrayList<>();
    er.findAll()
    .forEach(list::add);
    return list;
        //return list;
}


public void addEmployee(Employee e) {
    // TODO Auto-generated method stub

    er.save(e);

}


public String updateEmployee(Employee e, int id) {
    // TODO Auto-generated method stub
er.save(e);
    String s= "The Employee with id  has been replaced by Employee with id "+e.getId();
    return s;
}


public String deleteEmployee(int id) {
    //  Auto-generated method stub
    er.deleteById(id);
    return "Employee withh id "+id+" has been removed from the company";
}


public Employee getEmployee(int id) {
    return er.findById(id).get();
}


}

CrudRepository接口

package company.springBoot.io.Employee;

import org.springframework.data.repository.CrudRepository;

public interface EmployeeRepo extends CrudRepository<Employee, Integer>{

}

package company.springBoot.io.EmployeeRest;

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

@SpringBootApplication(scanBasePackages= 
{"company.springBoot.io.Employee"})
public class EmployeeRestApplication {

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

有人能帮我吗?

现在我得到了这个错误-


共1个答案

匿名用户

您缺少annnotation

package company.springBoot.io.Employee;

import org.springframework.data.repository.CrudRepository;
@Repository /// here is the trick
public interface EmployeeRepo extends CrudRepository<Employee, Integer>{

}

由于缺少注释,Spring没有扫描该接口,因此无法创建这种依赖关系。