Возникла проблема при создании bean-компонента для JpaRepository дочернего интерфейса как empRepository - PullRequest
0 голосов
/ 02 сентября 2018
2018-09-03 00:05:17.266  WARN 14948 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeServiceImpl': Unsatisfied dependency expressed through field 'employeeRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sathya.repository.EmployeeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-09-03 00:05:17.267  INFO 14948 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-09-03 00:05:17.285  INFO 14948 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-09-03 00:05:17.311  INFO 14948 --- [  restartedMain] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-09-03 00:05:17.559 ERROR 14948 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Описание:

Поле employeeRepository в com.sathya.service.EmployeeServiceImpl требуется компонент типа com.sathya.repository.EmployeeRepository, который не может быть найден.

Действие:

Рассмотрите возможность определения bean-компонента типа 'com.sathya.repository.EmployeeRepository' в вашей конфигурации.

Я получаю вышеуказанную ошибку для следующего кода:

package com.sathya.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.sathya.entity.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Integer>{
}

код класса сущности

package com.sathya.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="emp-tab")
public class Employee {

@Id
private Integer empid;
@Column(length=15)
private String ename;
private Integer salary;
private Double deptno;
public Integer getEmpid() {
    return empid;
}
public void setEmpid(Integer empid) {
    this.empid = empid;
}
public String getEname() {
    return ename;
}
public void setEname(String ename) {
    this.ename = ename;
}
public Integer getSalary() {
    return salary;
}
public void setSalary(Integer salary) {
    this.salary = salary;
}
public Double getDeptno() {
    return deptno;
}
public void setDeptno(Double deptno) {
    this.deptno = deptno;
}
@Override
public String toString() {
    return "Employee [empid=" + empid + ", ename=" + ename + ", salary=" + 
salary + ", deptno=" + deptno + "]";
}

}

application.yml

server:
   port: 4343
   context-path: /Ems
spring:
   datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/world
      username: root
      password: root
   jpa:
      show-sql: true
      hibernate:
      ddl-auto: update
   mvc:
      view:
         prefix: /
         suffix: .jsp

класс обслуживания и интерфейс

package com.sathya.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sathya.entity.Employee;
import com.sathya.repository.EmployeeRepository;
@Service
public class EmployeeServiceImpl implements IEmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public boolean insertEmployee(Employee e) {
    emp.save(e);
    return false;
}
}
-----------
package com.sathya.service;

import com.sathya.entity.Employee;

public interface IEmployeeService {
public boolean insertEmployee(Employee e);

}

контроллер класса

package com.sathya.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

 import com.sathya.entity.Employee;
 import com.sathya.service.IEmployeeService;

 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;

 @Controller
 public class EmployeeController {

@Autowired
private IEmployeeService service;
@GetMapping("/addEmployee")
public ModelAndView getEmployee()
{
    return new ModelAndView("AddEmployee");
}
@PostMapping("/insertEmployee")
public ModelAndView insertEmployee(HttpServletRequest request)
{
    Employee e=new Employee();
    e.setEmpid(Integer.parseInt(request.getParameter("empid")));
    e.setEname(request.getParameter("ename"));
    e.setSalary(Integer.parseInt(request.getParameter("salary")));
    e.setDeptno(Double.parseDouble(request.getParameter("deptno")));
    boolean flag=service.insertEmployee(e);
    if(flag==true)
        return new ModelAndView("index","message","Employee "+e.getEname()+"  
  Added to database...Successfully");
    else
        return new ModelAndView("index","message","Employee "+e.getEname()+"  
  is not Added to database..");
    }
 }

1 Ответ

0 голосов
/ 02 сентября 2018

Вы должны всегда следовать рекомендациям по кодированию.

Ниже приведены некоторые ошибки, которые вы делаете в отношении соглашения о кодировании.

@GetMapping("/AddEmployee") //change this to addEmployee

@Qualifier("empRepository") //no need of this line

private empRepository emp; //change this with below line of code rename the class

private EmployeeRepository employeeRepository;

см. Также https://docs.spring.io/spring-data/jpa/docs/1.6.0.RELEASE/reference/html/jpa.repositories.html#d0e1599

Если после внесения всех вышеперечисленных изменений также не работает, пожалуйста, сообщите мне.

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