【问题标题】:Unable to resolve BeanCreationException issue无法解决 BeanCreationException 问题
【发布时间】:2018-05-24 19:21:39
【问题描述】:

在运行应用程序时,尽管我的服务接口上有 @Service 注释,但它会引发无法为服务类创建 bean 的异常。我也包含了 context-component-scan-base-package 但它仍然无法扫描我的服务类包。 即使我将 @Service 注释放在我的服务类实现而不是我的服务类接口上,它也会给出相同的错误。组件扫描或服务类的自动装配存在问题。请帮忙

这是弹出的错误 错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'medicalController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.bhargav.mim.service.MedicalService com.bhargav.mim.rest.web.api.controller.MedicalController.medicalService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.bhargav.mim.service.MedicalService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:293)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)

MedicalController.java 控制器类:

package com.bhargav.mim.rest.web.api.controller;

import com.bhargav.mim.entity.Inventory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bhargav.mim.service.MedicalService;

import java.util.List;

@Controller
public class MedicalController {

  @Autowired
  private MedicalService medicalService;

  @RequestMapping(value = "/CompleteInventory", method = {RequestMethod.GET},
      produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public List<Inventory> getAllInventory(){
    return this.medicalService.getAllInventory();
  }

  @RequestMapping("/productName/{productName}")
  @ResponseBody
  public List<Inventory> searchByName(@PathVariable("productName") String productName){
    return medicalService.searchByName(productName);
  }


  @RequestMapping("/productName/{productID}")
  @ResponseBody
  public List<Inventory> searchByName(@PathVariable("productID") int productID){
    return medicalService.searchByID(productID);
  }

  @RequestMapping(value = "/addInventory", method = {RequestMethod.POST},
      produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public void addInventory(@RequestParam int productId,
      @RequestParam String productName, @RequestParam int productPrice, @RequestParam int
      productQuantity,
      @RequestParam String productCategory)
      throws Exception {
    Inventory inventory = new Inventory();
     inventory.setProductId(productId);
     inventory.setProductName(productName);
     inventory.setProductCategory(productCategory);
     inventory.setProductPrice(productPrice);
     inventory.setProductQuantity(productQuantity);
    this.medicalService.addInventory(inventory);
  }

  @RequestMapping(value = "/update", method = {RequestMethod.POST},
      produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public void updateCustomerRule(@RequestParam String productName, @RequestParam Double productPrice, @RequestParam int
      productQuantity,
      @RequestParam String productCategory, @PathVariable int productId)
      throws Exception {
    Inventory inventory = new Inventory();
    this.medicalService.updateInventory(inventory);
  }

  @RequestMapping(value = "/delete/{productId}", method = {RequestMethod.DELETE},
      produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public void deleteInventory(@PathVariable("productId") int productId)
      throws Exception {
    this.medicalService.deleteInventory(productId);
  }

  @RequestMapping("/productNameQueryBased/{productName}")
  @ResponseBody
  public List<Inventory> findByName(@PathVariable("productName") String productName){
    return medicalService.findByName(productName);
  }


  @RequestMapping("/productNameQueryBased/{productID}")
  @ResponseBody
  public List<Inventory> findByName(@PathVariable("productID") int productID){
    return medicalService.findByID(productID);
  }
}


**Service Interface**

package com.bhargav.mim.service;

import com.bhargav.mim.entity.Inventory;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public interface MedicalService {

  List<Inventory> getAllInventory();

  List<Inventory> searchByID(int productID);

  void addInventory(Inventory inventory);

  List<Inventory> searchByName(String productName);

  void updateInventory(Inventory inventory);

  void deleteInventory(int productID);

  List<Inventory> findByID(int productID);

  List<Inventory> findByName(String productName);

}



**Service Class Impl**

package com.bhargav.mim.service.Impl;

import com.bhargav.mim.dao.MedicalRepository;
import com.bhargav.mim.dao.MedicalRepositoryQueryBased;
import com.bhargav.mim.entity.Inventory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.bhargav.mim.service.MedicalService;
import org.springframework.stereotype.Service;

import java.util.List;

public class MedicalServiceImpl implements MedicalService {

  @Autowired
  private MedicalRepository medicalRepository;

  @Autowired
  private MedicalRepositoryQueryBased medicalRepositoryQueryBased;

  public List<Inventory> getAllInventory() {
      return (List<Inventory>) this.medicalRepository.findAll();
  }

  public List<Inventory> searchByID(int productID) {
    return this.medicalRepository.findByProductId(productID);
  }

  public void addInventory(Inventory inventory) {
    this.medicalRepository.save(inventory);

  }

  public List<Inventory> searchByName(String productName) {
    return this.medicalRepository.findByProductName(productName);
  }

  public void updateInventory(Inventory inventory) {
    Inventory savedInventory = this.medicalRepository.findOne(inventory.getProductId());
    BeanUtils.copyProperties(inventory, savedInventory);
    this.medicalRepository.delete(inventory.getProductId());
    this.medicalRepository.save(inventory);
  }

  public void deleteInventory(int productID){
    this.medicalRepository.delete(productID);
  }

  public List<Inventory> findByName(String productName) {
    return this.medicalRepositoryQueryBased.findByProductName(productName);
  }


  public List<Inventory> findByID(int productID) {
    return this.medicalRepositoryQueryBased.findByProductId(productID);
  }
}

**project-context.xml**

<beans
        xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
        xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.springframework.org/schema/beans">

    <!-- <context:component-scan base-package="org.product" /> -->
    <context:component-scan
            base-package="com.bhargav.mim">
    </context:component-scan>
    <mvc:annotation-driven />
    <tx:annotation-driven />

    <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
        <property value="org.postgresql.Driver" name="driverClassName" />
        <property value="jdbc:postgresql://localhost/testdb" name="url" />
        <property value="testuser" name="username" />
    </bean>
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

        <!-- THIS IS WHERE THE MODELS ARE -->
        <property name="packagesToScan" value="com.bhargav.mim.entity" />

        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
            </bean>
        </property>
        <property name="jpaProperties">
            <value>
                hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
                hibernate.cache.use_second_level_cache=true
            </value>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <jpa:repositories base-package="com.bhargav.mim.dao" />

    <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses">
        <list> <value>org.product.entity.Product</value> </list> </property> <property
        name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
        <prop key="hibernate.hbm2ddl.auto">create-drop</prop> <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.current_session_context_class">thread</prop> </props>
        </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" /> </bean> -->
</beans>

**web.xml**

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:project-context.xml</param-value>
        <param-value>classpath*:serviceContext.xml</param-value>
        <param-value>classpath*:persistenceContext.xml</param-value>
        <param-value>classpath*:entityContext.xml</param-value>

    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:project-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

【问题讨论】:

  • 我认为您需要将 MedicalServiceImpl 注释为@component

标签: java spring maven spring-mvc


【解决方案1】:

您需要使用@component@service 注释您的MedicalServiceImpl 类,并从interface 中删除注释

你不需要注释你的界面

public interface MedicalService {

  List<Inventory> getAllInventory();

  List<Inventory> searchByID(int productID);

  void addInventory(Inventory inventory);

  List<Inventory> searchByName(String productName);

  void updateInventory(Inventory inventory);

  void deleteInventory(int productID);

  List<Inventory> findByID(int productID);

  List<Inventory> findByName(String productName);

}

【讨论】:

    【解决方案2】:

    我认为您在 spring-servlet.xml 文件中缺少 context:annotation-config 。 只需在组件扫描标签之前添加该标签。它应该可以工作。

    还要从接口中删除@Service 注释并将该注释添加到实现类。 如果它不起作用,请告诉我。

    【讨论】:

    • 感谢您的回答。但它仍然显示同样的问题。
    • 能否在 web.xml 的完整路径中提供你的 project-context.xml 的路径。在 web.xml 中,您使用了具有配置文件路径的 contextconfiglocation 参数。你能把路径改成/WEB-INF/project-context.xml吗?
    【解决方案3】:

    这里有很多答案。所有这些都将起作用。在这种情况下,您拥有的是一项服务。

    • 我们可以对它进行分类,而不仅仅是一个组件 (@Component)
    • 它不是存储库 (@Repository),它不直接与数据层交互。
    • 这显然不是控制器 (@Controller)。

    请在此处阅读更多内容以了解它们:What's the difference between @Component, @Repository & @Service annotations in Spring?

    @Service // Add this
    public class MedicalServiceImpl implements MedicalService {
       //...
    }
    

    您还可以从界面中删除注释。您的界面只允许您定义 bean 的“形状”。它本身并没有做任何动作。它允许另一个开发人员出现并创建一个新的实现,并删除旧的。这使他们能够遵守接口,确保无论在何处定义该接口,应用程序逻辑都将继续工作。

    【讨论】:

      【解决方案4】:

      只需如下更新您的服务实现

      @Service
      public class MedicalServiceImpl implements MedicalService {
      
        @Autowired
        private MedicalRepository medicalRepository;
      
        @Autowired
        private MedicalRepositoryQueryBased medicalRepositoryQueryBased;
      
        public List<Inventory> getAllInventory() {
            return (List<Inventory>) this.medicalRepository.findAll();
        }
      
        public List<Inventory> searchByID(int productID) {
          return this.medicalRepository.findByProductId(productID);
        }
      
        public void addInventory(Inventory inventory) {
          this.medicalRepository.save(inventory);
      
        }
      
        public List<Inventory> searchByName(String productName) {
          return this.medicalRepository.findByProductName(productName);
        }
      
        public void updateInventory(Inventory inventory) {
          Inventory savedInventory = this.medicalRepository.findOne(inventory.getProductId());
          BeanUtils.copyProperties(inventory, savedInventory);
          this.medicalRepository.delete(inventory.getProductId());
          this.medicalRepository.save(inventory);
        }
      
        public void deleteInventory(int productID){
          this.medicalRepository.delete(productID);
        }
      
        public List<Inventory> findByName(String productName) {
          return this.medicalRepositoryQueryBased.findByProductName(productName);
        }
      
      
        public List<Inventory> findByID(int productID) {
          return this.medicalRepositoryQueryBased.findByProductId(productID);
        }
      }
      

      并从您的界面中删除 @Service 注释。

      【讨论】:

        【解决方案5】:

        请在MedicalServiceImpl类上使用@component注解

        @Component // Add this
        public class MedicalServiceImpl implements MedicalService {
           //...
        }
        

        【讨论】:

          猜你喜欢
          • 2021-05-17
          • 1970-01-01
          • 2022-01-10
          • 2016-10-16
          • 2017-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多