【问题标题】:Spring-MVC - Error creating bean with name 'productsController': Injection of autowired dependencies failedSpring-MVC - 创建名为“productsController”的 bean 时出错:注入自动装配的依赖项失败
【发布时间】:2015-09-05 21:11:03
【问题描述】:

我的 spring-mvc 项目有问题。 @autowireing 没有创建所需的 bean。我已经为此工作了超过 4 天,并跟踪了所有搜索结果。但没有任何效果。有人可以看看。谢谢你

错误堆栈是这样的:

org.springframework.beans.factory.BeanCreationException:创建名为“productsController”的bean时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:私有 com.davis.ty.service.ProductsService com.davis.ty.controller.ProductsController.productsService;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为 [com.davis.ty.service.ProductsService] 的合格 bean:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)

我的 servlet.xml 是:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        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">


    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    <context:annotation-config />
    <context:component-scan base-package="com.davis.ty" />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="dataSource"
        class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

我的控制器是:

package com.davis.ty.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.davis.ty.domain.Products;
import com.davis.ty.service.ProductsService;

@Controller 
public class ProductsController {

    @Autowired 
    private ProductsService productsService;

     @RequestMapping(value = "/index", method = RequestMethod.GET)
     public String listProducts (Map<String, Object> map) {

         System.out.println("index");

            map.put("products", new Products());
            map.put("productsList", productsService.listProducts());

            return "index";
     }     


    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addProducts(@ModelAttribute("products")
        Products products, BindingResult result) {

            productsService.addProducts(products);

            return "redirect:/index";
        }

    @RequestMapping("/delete/{Id}")
    public String deleteProducts(@PathVariable("Id")
        Integer Id) {

            productsService.removeProducts(Id);

            return "redirect:/index";
        }
}       

我的服务程序是:

package com.davis.ty.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.davis.ty.dao.ProductsDAO;
import com.davis.ty.domain.Products;

@Service
public class ProductsServiceImpl {

    @Autowired
    private ProductsDAO productsDAO;

    @Transactional
    public void addProducts(Products products){

        productsDAO.addProduct(products);
    }

    @Transactional
    public List<Products> listProducts() {

        return productsDAO.listProducts();

    }

    @Transactional
    public void removeProducts(Integer id) {

        productsDAO.removeProducts(id);

    }
}   

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    创建一个服务接口,并在服务Impl类中使用@Overrride注解实现接口方法。

    public interface ProductService{
    
     List<Product> getProducts();
    
    }
    

    然后

    @Service
    public class ProductsServiceImpl implements  ProductService{
    
    @Override
    public List<Product> getProducts() {
        return productRepository.findAll();
    }
     
    

    【讨论】:

      【解决方案2】:

      public class ProductsServiceImpl之后添加implements ProductService

      【讨论】:

        【解决方案3】:

        Spring autowire 的工作原理是,Spring 应用程序上下文扫描包和子包中的所有类,由组件扫描指定,并在内部按类型和名称创建映射。在类型的情况下,值可以是实现类的列表,并按其名称命名。

        那么每当遇到@Autowire 时,

        • 首先它按类型检查,所以如果你使用接口自动装配,它会检查该接口的所有实现,如果只有 1 个,则注入相同的。 (如果找到超过 1 个,则需要使用 Qualifier 进行 qaulify 并给出正确的名称。

        • 如果上述失败,如果按名称检查,则注入。

        如果两者都失败,如果给出NoSuchBeanDefinitionException,

        所以在你的情况下,你已经设置了组件扫描,这是正确的。然后在自动装配时,您给出接口类名称,而实现类不实现接口。所以类型检查失败,并且按名称也失败了,因此你得到了 NoSuchBeanDefinitionException。

        要解决这个问题,您需要按照@JB Nizet 的建议进行操作,以便 #1 工作并且 bean 被正确注入。

        【讨论】:

          【解决方案4】:

          根据我的经验,我只是在我的 DAO 中添加了@Repository,也许你也可以尝试使用它

          @Repository
          public class ProductsDAO
          {
          }
          

          【讨论】:

            【解决方案5】:

            好吧,您的 ProductsServiceImpl 类没有实现 ProductsService... 所以无法将 bean 注入到 ProductsService 类型的字段中。

            【讨论】:

            • 非常感谢您的回复。
            • 我不相信这一点,但我得到了完全相同的错误。但我无法选择发布或清理服务器工作区。我想这可能与此有关。我正在努力。当我进行更改以实现接口时,我的项目已经失控了。 Eclipse 甚至不将它们视为服务器,就像另一个项目一样
            猜你喜欢
            • 1970-01-01
            • 2017-09-24
            • 1970-01-01
            • 1970-01-01
            • 2015-12-06
            • 2019-06-10
            • 2014-06-09
            • 2012-04-25
            • 2018-06-22
            相关资源
            最近更新 更多