【问题标题】:Error creating bean with name 'locationController': Unsatisfied dependency expressed through field 'service'; nested exception创建名称为“locationController”的 bean 时出错:通过字段“服务”表达的依赖关系不满足;嵌套异常
【发布时间】:2019-02-20 14:31:53
【问题描述】:

我是 Spring 新手,所以我指的是一些关于 Spring Boot 的实时项目教程。他们正在使用 JFreeChart 创建饼图。因此,每当我在我的主代码中包含饼图代码时,我在开发它时都会遇到问题,我的程序面临一些错误。 如果我的程序中没有包含饼图代码,我的程序运行良好。 如果我删除 repositoy 类中的代码,我的代码运行良好。请帮帮我。

错误

  main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.5.Final}
2018-09-16 18:28:04.591  INFO 6860 --- [           main] 
org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2018-09-16 18:28:04.761  INFO 6860 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2018-09-16 18:28:04.905  INFO 6860 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-09-16 18:28:05.512  INFO 6860 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-09-16 18:28:05.817  INFO 6860 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2018-09-16 18:28:05.862  WARN 6860 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'locationController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'LocationService': Unsatisfied dependency expressed through field 'locationRepos'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'locationRepos': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.project.abhishek.location.repos.LocationRepos.findTypeAndTypeCount()!
2018-09-16 18:28:05.862  INFO 6860 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-09-16 18:28:05.862  INFO 6860 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2018-09-16 18:28:05.867  INFO 6860 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2018-09-16 18:28:05.872  INFO 6860 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-09-16 18:28:05.887  INFO 6860 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
 2018-09-16 18:28:05.897 ERROR 6860 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'locationController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'LocationService': Unsatisfied dependency expressed through field 'locationRepos'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'locationRepos': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.project.abhishek.location.repos.LocationRepos.findTypeAndTypeCount()!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:598) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1376) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:829) ~[spring-beans-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:865) ~[spring-context-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548) ~[spring-context-5.1.0.RC2.jar:5.1.0.RC2]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.1.0.M2.jar:2.1.0.M2]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:785) [spring-boot-2.1.0.M2.jar:2.1.0.M2]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:418) [spring-boot-2.1.0.M2.jar:2.1.0.M2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:337) [spring-boot-2.1.0.M2.jar:2.1.0.M2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1269) [spring-boot-2.1.0.M2.jar:2.1.0.M2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1257) [spring-boot-2.1.0.M2.jar:2.1.0.M2]
at com.project.abhishek.location.StudentApplication.main(StudentApplication.java:16) [classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'LocationService': Unsatisfied dependency 

应用类

@SpringBootApplication
@ComponentScan("com.project.abhishek.location")

public class StudentApplication {

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

存储库类

public interface LocationRepos extends JpaRepository<Location, Integer> {

@Query("select type,count(type) from location group by type")
public List<Object[]> findTypeAndTypeCount(); 
}

控制器

@Controller
public class LocationController {

@Autowired
private LocationService service;

@RequestMapping("/saveLoc")
public String saveLocation(@ModelAttribute("location") Location location, ModelMap modelMap) {
    Location locationSaved = getService().saveLocation(location);

    String msg = "Location save with id:" +locationSaved.getId();
    modelMap.addAttribute("msg", msg);
    return "createLocation";
}
@RequestMapping("/displayLocation")
public String displayLocation(ModelMap modelMap) {
    List<Location> locations = service.getAllLocation();
    modelMap.addAttribute("locations", locations);
    return "displayLocation";
}

@RequestMapping("/deleteLocation")
public String deleteLocation(@RequestParam("id")int id,ModelMap modelMap ) {
    Location location = new Location();
    location.setId(id);
    service.deleteLocation(location);
    List<Location> locations = service.getAllLocation();
    modelMap.addAttribute("locations", locations);
    return "displayLocation";

}

@RequestMapping("/generateReport")
public String generateReport() {
    String path =context.getRealPath("/");
    List<Object[]> data = locationRepos.findTypeAndTypeCount();
    reportUtill.generatePieChart(path, data);
    return "report";
}
public LocationService getService() {
    return service;
}

public void setService(LocationService service) {
    this.service = service;
}

服务类

@Service
public class LocationServiceImpl implements LocationService {

@Autowired
private LocationRepos locationRepos;

@Override
public Location saveLocation(Location location) {

    return locationRepos.save(location);
}

@Override
public Location updateLocation(Location location) {
    return locationRepos.save(location);
}

@Override
public void deleteLocation(Location location) {
    locationRepos.delete(location);
}

@Override
public Location getLocation(int id) {
    Optional<Location> optional = locationRepos.findById(id);
    Location location = optional.get();
    return location;
}

@Override
public List<Location> getAllLocation() {
    return locationRepos.findAll();
}

public LocationRepos getLocationRepos() {
    return locationRepos;
}

public void setLocationRepos(LocationRepos locationRepos) {
    this.locationRepos = locationRepos;
}

}

实体

@Entity
public class Location {

@Id
private int id;
private String code;
private String name;
private String type;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

@Override
public String toString() {
    return "Location [id=" + id + ", code=" + code + ", name=" + name + ", type=" + type + "]";
}

ReportUtil 类

@Component
public class ReportUtilImpl implements ReportUtil {

@Override
public void generatePieChart(String path, List<Object[]> data) {

    DefaultPieDataset dataset= new DefaultPieDataset();
    for (Object[] object : data) {
        dataset.setValue(object[0].toString(), new Double(object[1].toString()));
    }
    JFreeChart chart = ChartFactory.createPieChart3D("Location Type report", dataset, true, true, false);

    try {
        ChartUtilities.saveChartAsJPEG(new File(path+"/pieChart.jpeg"), chart, 300, 300);
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

}

我的包结构是

com.project.abhishek.location---application classs  
com.project.abhishek.location.controller---controller class  
com.project.abhishek.location.entity---entity class  
com.project.abhishek.location.repos---repository class  
com.project.abhishek.location.service---service class 
com.project.abhishek.location.util---ReportUtil class
com.project.abhishek.location.repos---repository class

【问题讨论】:

  • 要么使用@EnableAutoConfiguration,要么使用@EnableJpaRespositories(basePackageScan="com.repository.package")
  • 两个注释都尝试了同样的错误
  • 另外你的仓库类应该用@Repository注解。
  • 不,它不应该有@Repository。错误是说Validation failed for query,这意味着它不能使用@Query。我的猜测是Location 需要大写(这是 JPQL,不是 SQL)。
  • @chrylis-onstrike- 非常感谢你。从来没想过大写。

标签: java spring spring-mvc spring-boot spring-data-jpa


【解决方案1】:

我认为主要问题是你在@Query() 中的 sql,你有两种方法来修复它

第一个是将查询更改为原生查询。

public interface LocationRepos extends JpaRepository<Location, Integer> {

@Query("select type,count(type) from location group by type", nativeQuery = true)
public List<Object[]> findTypeAndTypeCount(); 
}

第二个是满足JQL的要求

public interface LocationRepos extends JpaRepository<Location, Integer> {

@Query("select lc.type,count(lc.type) from Location lc group by lc.type")
public List<Object[]> findTypeAndTypeCount(); 
}

【讨论】:

  • 感谢clevertension "@Query(value = "select type,count(type) from location group by type", nativeQuery = true)" 这行得通,但我能知道为什么。我是新手,请帮帮我
  • 默认Query是一个JPQL,和native sql不同,可以参考docs.jboss.org/hibernate/orm/4.3/devguide/en-US/html/ch11.html,当我们加上nativeQuery = true,Query中的sql就是数据库中的sql
【解决方案2】:

@clevertension 是对的,主要问题出在 SQL 查询中,编写 nativeQuery = true 确实解决了问题,但他的答案中缺少 value 字段,因此我遇到了错误。 所以我的解决方案是

public interface LocationRepos extends JpaRepository<Location, Integer> {

@Query(value = "select type,count(type) from location group by type", nativeQuery = true)
public List<Object[]> findTypeAndTypeCount(); 
}

【讨论】:

    【解决方案3】:

    Spring 无法创建 bean,因为 LocationRepository 已经注入到我的服务类中,因此在控制器标志中显式注入 LocationRepository。这是我的解决方案:

    @Repository
    public interface LocationRepository extends JpaRepository<Location, Integer> {
    
        public static final String LOCATION_TYPE_COUNT = "select type, count(type) from location_tbl group by type";
    
        @Query(value = LOCATION_TYPE_COUNT, nativeQuery = true)
        public List<Object[]> findTypeAndCount();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2019-08-07
      • 2019-02-22
      • 2019-10-11
      相关资源
      最近更新 更多