无法解决BeanCreationException问题

时间:2017-12-11 09:45:29

标签: java spring maven spring-mvc

在运行应用程序时,虽然我的服务接口上有@Service注释,但它抛出了无法为服务类创建bean的异常。我也包含了context-component-scan-base-package,但仍然无法扫描我的服务类包。 即使我将@Service注释放在我的Service类实现而不是我的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>

5 个答案:

答案 0 :(得分:0)

请在MedicalServiceImpl

上使用@component注释
@Component // Add this
public class MedicalServiceImpl implements MedicalService {
   //...
}

答案 1 :(得分:0)

您需要使用MedicalServiceImpl@component@service课程添加注释,并从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 :(得分:0)

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

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

答案 3 :(得分:0)

这里有很多答案。他们都会工作。在这种情况下,您所拥有的是一项服务。

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

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

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

您也可以从界面中删除注释。您的界面只允许您定义&#34; Shape&#34;你的豆子它本身并没有采取任何行动。它允许另一个开发人员出现并创建一个新的实现,并删除旧的实现。这允许它们遵循接口,确保无论在何处定义接口,应用程序逻辑都将继续工作。

答案 4 :(得分:0)

只需更新您的服务实施,如下所示

@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注释。