Spring mvc Spring MVC-创建名为';产品控制器';:自动关联依赖项的注入失败

Spring mvc Spring MVC-创建名为';产品控制器';:自动关联依赖项的注入失败,spring-mvc,Spring Mvc,我对SpringMVC项目有问题。@autowiring没有创建所需的bean。我为此工作了4天多,跟踪了所有的搜索结果。但一切都没有奏效。谁能看一下吗。多谢各位 错误堆栈如下所示: org.springframework.beans.factory.BeanCreationException:创建名为“productsController”的bean时出错:自动关联依赖项的注入失败;嵌套异常为org.springframework.beans.factory.BeanCreationExcep

我对SpringMVC项目有问题。@autowiring没有创建所需的bean。我为此工作了4天多,跟踪了所有的搜索结果。但一切都没有奏效。谁能看一下吗。多谢各位

错误堆栈如下所示:

org.springframework.beans.factory.BeanCreationException:创建名为“productsController”的bean时出错:自动关联依赖项的注入失败;嵌套异常为org.springframework.beans.factory.BeanCreationException:无法自动关联字段:private com.davis.ty.service.ProductsService com.davis.ty.controller.ProductsService;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到依赖项类型为[com.davis.ty.service.ProductsService]的符合条件的bean:至少需要1个符合此依赖项autowire候选项条件的bean。依赖项注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} org.springframework.beans.factory.annotation.AutoWiredNotationBeanPostProcessor.PostProcessPropertyValue(AutoWiredNotationBeanPostProcessor.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>

类路径:hibernate.cfg.xml
org.hibernate.cfg.AnnotationConfiguration
${jdbc.dial}
真的
我的控制器是:

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";
        }
}       
包com.davis.ty.controller;
导入java.util.Map;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Controller;
导入org.springframework.validation.BindingResult;
导入org.springframework.web.bind.annotation.ModelAttribute;
导入org.springframework.web.bind.annotation.PathVariable;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.springframework.web.bind.annotation.RequestMethod;
导入com.davis.ty.domain.Products;
导入com.davis.ty.service.ProductsService;
@控制器
公共类产品控制器{
@自动连线
私人产品服务产品服务;
@RequestMapping(value=“/index”,method=RequestMethod.GET)
公共字符串listProducts(映射){
系统输出打印项次(“索引”);
map.put(“产品”,新产品());
map.put(“productsList”,productsService.listProducts());
返回“索引”;
}     
@RequestMapping(value=“/add”,method=RequestMethod.POST)
公共字符串addProducts(@modeldattribute(“产品”)
产品、BindingResult(结果){
productsService.addProducts(产品);
返回“重定向:/index”;
}
@请求映射(“/delete/{Id}”)
公共字符串deleteProducts(@PathVariable(“Id”)
整数Id){
产品服务移除产品(Id);
返回“重定向:/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);

    }
}   
package com.davis.ty.service;
导入java.util.List;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Service;
导入org.springframework.transaction.annotation.Transactional;
导入com.davis.ty.dao.ProductsDAO;
导入com.davis.ty.domain.Products;
@服务
公共类产品服务impl{
@自动连线
私人产品;
@交易的
公共产品(产品){
productsDAO.addProduct(产品);
}
@交易的
公共列表产品(){
返回productsDAO.listProducts();
}
@交易的
public void removeProducts(整数id){
productsDAO.removeProducts(id);
}
}   

好吧,您的
ProductsServiceImpl
类没有实现
ProductsService
。。。因此,bean不可能被注入到
ProductsService

类型的字段中。那么,您的
ProductsServiceImpl
类不实现
ProductsService
。。。根据我的经验,bean不可能被注入到
ProductsService

类型的字段中,我只是在我的DAO中添加了
@Repository
,也许你也可以尝试使用它

@Repository
public class ProductsDAO
{
}

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

@Repository
public class ProductsDAO
{
}

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

然后每当遇到@Autowire时

  • 首先,它会按类型进行检查,所以如果您使用接口autowire,它会检查该接口的所有实现,如果只找到1,则会注入相同的实现。(如果找到的数量超过1,则需要使用限定符进行qaulify并给出正确的名称

  • 如果上述操作失败,则按名称进行检查,并进行注入

如果两者都失败,如果没有给出这样的定义异常

因此,在您的情况下,您已经设置了组件扫描,这是正确的。然后,在自动关联时,您正在提供接口类名称,而实现类未实现接口。因此,类型检查失败,并且by name也失败,因此您将获得NoSuchBeanDefinitionException


要解决这个问题,您需要按照@JB Nizet的建议来做,这样#1就能正常工作,bean就能正确注入。

Spring autowire的工作原理是,Spring应用程序上下文扫描包和子包内的所有类,这些类由组件扫描指定,并在内部按类型和名称创建一个映射。如果是类型,值可以是be实现类的列表,以及
@Service
public class ProductsServiceImpl implements  ProductService{

@Override
public List<Product> getProducts() {
    return productRepository.findAll();
}