1

在创建我的 bean 时,我不断收到以下错误,但是我不确定为什么在声明它时它没有看到 bean。文件结构有问题还是有更深层次的问题?我知道这对很多人来说都是 TLDR,但我想包括完整的流程。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productsController' defined in file [C:\Users\ChappleZ\Desktop\CRCart001\CRCartSpring001\out\artifacts\CRCartSpring001_war_exploded\WEB-INF\classes\cr\controllers\ProductsController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [cr.managers.ProductsManager]: : No matching bean of type [cr.managers.ProductsManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [cr.managers.ProductsManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

下面是文件夹结构和相关文件。

 
源代码
- 爪哇
     |_ 铬
          |_ 控制器
               |_ 产品控制器
          |_ 道
               |_ 实现
                    |_ 产品介绍DaoImpl
          |_ 产品中心
          |_ 实体
               |_ 产品
          |_ 经理
               |_ 产品经理
               |_ 实现
                    |_ ProductsManagerImpl
- 资源
     |_ 豆子
          |_ 道斯.xml
          |_ 服务.xml
     |_ 配置
          |_ BeanLocations.xml
     |_ 数据库
          |_ 数据源.xml
          |_ 休眠.xml
     |_ 属性
          |_ 数据库.properties

网络
- 资源
     |_ 组件
     |_ CSS
     |_ 数据
     |_ 图像
     |_ js
     |_ 观看次数
- 网络信息
     |_ applicationContext.xml
     |_ 调度程序-servlet.xml
     |_ 日志记录.properties
     |_ web.xml
- index.jsp

产品控制器

package cr.controllers;

import cr.Entity.Products;
import cr.managers.ProductsManager;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;

@Controller
@RequestMapping("/Products")
public class ProductsController {
    private ProductsManager productsManager;

    @Autowired
    public ProductsController(ProductsManager productsManager) {
        this.productsManager = productsManager;
    }

    @RequestMapping(
            value = "/products/{productId}",
            method = RequestMethod.GET)
    public
    @ResponseBody
    Products findByProductId(@PathVariable long productId) {
        Products products = productsManager.findByProductId(productId);
        return products;
    }
}

产品DaoImpl

package cr.dao.impl;

import cr.Entity.Products;
import cr.dao.ProductsDao;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.List;

public class ProductsDaoImpl extends HibernateDaoSupport implements ProductsDao {
    @Override
    public void save(Products products) {
        getHibernateTemplate().save(products);
    }

    @Override
    public void update(Products products) {
        getHibernateTemplate().update(products);
    }

    @Override
    public void delete(Products products) {
        getHibernateTemplate().delete(products);
    }

    @Override
    public Products findByProductId(Long productId) {
        List list = getHibernateTemplate().find("from Products where productId=?",productId);
        return (Products)list.get(0);
    }
}

产品道

package cr.dao;

import cr.Entity.Products;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
public interface ProductsDao {
    void save(Products products);

    void update(Products products);

    void delete(Products products);

    Products findByProductId(Long productId);
}

产品实体

package cr.Entity;

import com.sun.istack.internal.NotNull;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

import javax.persistence.*;
import java.sql.Timestamp;

@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name= "Products")
public class Products {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name= "productsId")
    private int productsId;

    @Column(name = "ProductName")
    @NotNull
    private String productName;

    @Column(name = "ProductDescription")
    @NotNull
    private String productDescription;

    @Column(name = "MfgCost")
    private double mfgCost;

    @Column(name = "Price")
    private double price;

    @Column(name = "SalePrice")
    private double salePrice;

    @Column(name = "CreationDate")
    private Timestamp creationDate;

    @Column(name = "DeletedIndicator")
    private Boolean deletedIndicator;

    @Column(name = "ImagePath")
    @NotNull
    private String imagePath;

+Setters and Getters + ToString (Not added to keep post shorter)

产品经理

package cr.managers;

import cr.Entity.Products;

public interface ProductsManager {
    void save(Products products);

    void update(Products products);

    void delete(Products products);

    Products findByProductId(Long productId);
}

ProductsManagerImpl

package cr.managers.impl;

import cr.Entity.Products;
import cr.dao.ProductsDao;
import cr.managers.ProductsManager;

public class ProductsManagerImpl implements ProductsManager{
    ProductsDao productsDao;

    public void setProductsDao(ProductsDao productsDao){
        this.productsDao=productsDao;
    }

    public void save(Products products) {
        productsDao.save(products);
    }

    public void update(Products products) {
        productsDao.update(products);
    }

    public void delete(Products products) {
        productsDao.delete(products);
    }

    public Products findByProductId(Long productId) {
        return productsDao.findByProductId(productId);
    }
}

道斯.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- Products Data Access Object -->
    <bean id="productsDao" class="cr.dao.impl.ProductsDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

</beans>

服务.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- Products object -->
    <bean id="productsManager" class="cr.managers.impl.ProductsManagerImpl">
        <property name="productsDao" ref="productsDao"/>
    </bean>

</beans>

BeanLocations.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- Database Configuration -->
    <import resource="../database/DataSource.xml"/>
    <import resource="../database/Hibernate.xml"/>


    <!-- Beans Declaration -->
    <import resource="../beans/daos.xml"/>
    <import resource="../beans/services.xml"/>
</beans>

数据源.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>properties/database.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

</beans>

休眠.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>

    </bean>

</beans>

数据库属性

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/schema
jdbc.username=user
jdbc.password=root

应用程序上下文.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

调度程序-servlet.xml

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

    <!--================================= Component Scan ======================================-->
    <!-- Scans within the base package of the application for @Controller to configure as beans -->
    <!-- This entry looks for annotated classes and provides those beans in the Spring container.   -->
    <!-- So there is no need to declare bean definitions in the XML configuration -->
    <context:component-scan base-package="cr"/>

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

    <mvc:annotation-driven />


    <!--SimpleUrlHandlerMapping is already configured, disabling the default HandlerMappings.
     The DispatcherServlet enables the DefaultAnnotationHandlerMapping, which looks for @RequestMapping annotations on @Controllers. -->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <!-- Based on the value of the order property Spring sorts all handler mappings available in the context and applies the first matching handler. -->
        <property name="order" value="1"/>
    </bean>

</beans>

日志记录属性

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           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>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>
4

3 回答 3

2
  1. 您的 applicationContext.xml 不会导入任何带有 bean 定义的 XML 文件,因此不会处理这些文件
  2. 您的 MVC 调度程序 servlet 扫描“cr”包以查找带有 Spring 注释的类。您的 ProductsManager 类没有注释,因此无法通过组件扫描找到,但 ProductsController 类已找到,并且无法实例化,因为 Spring 不知道您的 ProductsManager 类。

建议:

在主应用程序上下文中导入 bean 定义 XML。不要在根上下文中实例化 ProductsController - 所有 @Controller bean 都应该属于 MVC servlet 上下文。您可以使用 MVC xml 中的以下标记来实现此目的:

<context:component-scan base-package="cr" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

并在主要上下文中向您的类添加 @Component 注释并使用它:

<context:component-scan base-package="cr" use-default-filters="true">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

或完全跳过组件扫描并在 XML 中手动定义您的 bean

于 2013-02-13T19:19:09.393 回答
2

这是您得到错误的地方:

private ProductsManager productsManager;

@Autowired
public ProductsController(ProductsManager productsManager) {
    this.productsManager = productsManager;
}

这不是自动装配 bean 的正确方法。

将所有这些替换为

@Autowired
private ProductsManager productsManager;

您不必为此创建构造函数。或者,您可以在 setter 上自动装配 bean:

private ProductsManager productsManager;

@Autowired
public setProductsManager(ProductsManager productsManager) {
    this.productsManager = productsManager;
}
于 2013-02-14T10:28:50.820 回答
0

选项1:-

在 web.xml 中加载 services.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
 //Load Services.xml here like <param-value>actualPath/services.xml</param-value>
</context-param>

在 service.xml 中导入 dao.xml

//Like <import resource="classpath:actualClassPath/dao.xml" />

然后

您可以直接在控制器中自动装配 productsManager。您可以直接在 productsManager 中自动装配 productsDao。

由于您自动装配 productsManager,因此控制器中不需要构造函数。由于您自动装配 productsDao,因此 productsManager 中不需要构造函数。

下面的 bean 配置就足够了。

<bean id="productsManager" class="cr.managers.impl.ProductsManagerImpl"/>

下面的代码对于控制器来说已经足够了。

@Controller
@RequestMapping("/Products")
public class ProductsController {
 @Autowired    
 private ProductsManager productsManager;

 @RequestMapping(value = "/products/{productId}",
                    method = RequestMethod.GET)

 @ResponseBody
 public Products findByProductId(@PathVariable long productId) {
    Products products = productsManager.findByProductId(productId);
    return products;
  }
 }

选项2:-(我不推荐这个(这是为了更好地理解))

在 applicationContext.xml 中定义 productsManager,productsDao bean

然后

像上面的代码一样修改控制器它将起作用。

于 2013-02-14T12:07:59.200 回答