注入自动连接的依赖项失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:

时间:2017-03-16 11:09:21

标签: java spring hibernate maven spring-mvc

我是新手,我正在尝试使用Spring创建一个电子商店,但我遇到了与数据库连接的问题。我搜索并发现其他用户问同样的事情,但我找不到问题。我缺乏想法,这里有什么不对。

堆栈跟踪:

  

org.springframework.beans.factory.BeanCreationException:错误   创建名为'homeController'的bean:注入自动装配   依赖失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire字段:private dao.ProductDao   controllers.HomeController.productDao;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   为依赖项找到的[dao.ProductDao]类型的限定bean:   预计至少有1个豆有资格成为autowire候选人   这种依赖。   依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

源代码:

控制器

package controllers;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import dao.ProductDao;
import model.Product;

@Controller
public class HomeController {

@Autowired
private ProductDao productDao;

@RequestMapping("/")
public String home(){
    return "home";
}

@RequestMapping("/productList")
public String getProducts(Model model) {
    List<Product> products = productDao.getAllProducts();
    model.addAttribute("products", products);

    return "productList";
}

@RequestMapping("/productList/viewProduct/{productId}")
public String viewProduct(@PathVariable String productId, Model model) throws IOException{

    Product product = productDao.getProductById(productId);
    model.addAttribute(product);
    return "viewProduct";
}

}

ProductDao这个

package dao;
import java.util.List;
import org.springframework.stereotype.Component;
import model.Product;
public interface ProductDao {
    void addProduct(Product product);
    Product getProductById(String id);
    List<Product> getAllProducts();
    void deleteProduct(String id);
}

ProductdaoImpl

    package dao.impl;

    import java.util.List;

    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Transactional;

    import dao.ProductDao;
    import model.Product;

    @Repository
    @Transactional
    public class ProductDaoImpl implements ProductDao {

        @Autowired
        private SessionFactory sessionFactory;

        public void addProduct(Product product) {
            Session session = sessionFactory.getCurrentSession();
            session.saveOrUpdate(product);
            session.flush();
        }

        public Product getProductById(String id) {
            Session session = sessionFactory.getCurrentSession();
            Product product = (Product) session.get(Product.class, id);
            session.flush();

            return product;
        }

        public List<Product> getAllProducts() {
            Session session = sessionFactory.getCurrentSession();
            Query query = session.createQuery("from Product");
            List<Product> products = query.list();
            session.flush();

            return products;
        }

        public void deleteProduct(String id) {
            Session session = sessionFactory.getCurrentSession();
            session.delete(getProductById(id));
            session.flush();
        }
    }

实体(产品)

    package model;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;

    @Entity
    public class Product {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private String productId;
        private String productName;
        private String productCategory;
        private String productDescription;
        private double productPrice;
        private String productCondition;
        private String productStatus;
        private int unitInStock;
        private String productManufacture;

        public String getProductId() {
            return productId;
        }

        public void setProductId(String productId) {
            this.productId = productId;
        }

        public String getProductName() {
            return productName;
        }

        public void setProductName(String productName) {
            this.productName = productName;
        }

        public String getProductCategory() {
            return productCategory;
        }

        public void setProductCategory(String productCategory) {
            this.productCategory = productCategory;
        }

        public String getProductDescription() {
            return productDescription;
        }

        public void setProductDescription(String productDescription) {
            this.productDescription = productDescription;
        }

        public double getProductPrice() {
            return productPrice;
        }

        public void setProductPrice(double productPrice) {
            this.productPrice = productPrice;
        }

        public String getProductCondition() {
            return productCondition;
        }

        public void setProductCondition(String productCondition) {
            this.productCondition = productCondition;
        }

        public String getProductStatus() {
            return productStatus;
        }

        public void setProductStatus(String productStatus) {
            this.productStatus = productStatus;
        }

        public int getUnitInStock() {
            return unitInStock;
        }

        public void setUnitInStock(int unitInStock) {
            this.unitInStock = unitInStock;
        }

        public String getProductManufacture() {
            return productManufacture;
        }

        public void setProductManufacture(String productManufacture) {
            this.productManufacture = productManufacture;
        }

    }

jdbc.properties

  jdbc.username = ****
  jdbc.password = ****
  jdbc.driver = com.mysql.jdbc.Driver
  jdbc.url = jdbc:mysql://localhost:3306/myeshop

的applicationContext.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:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        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-4.1.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

        <beans profile="dev">
            <context:property-placeholder
                location="properties/jdbc.properties" />
            <bean id="dataSource"
                class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                <property name="driverClassName" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="password" value="${jdbc.password}"></property>
                <property name="username" value="${jdbc.username}"></property>
            </bean>

            <bean id="sessionFactory"
                class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
                <property name="dataSource" ref="dataSource"></property>
                <property name="hibernateProperties">
                    <props>
                        <prop key="hibernate.diaect">org.hibernate.dialect.MySQL5Dialect</prop>
                        <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> 
                             <prop key="hibernate.show_sql">true</prop>
                             <prop key="hibernate.format_sql">tru</prop>
                        -->
                    </props>
                </property>
                <property name="packagesToScan">
                    <list>
                        <value>dao</value>
                    </list>
                </property>
            </bean>

    <!-- Exei alli klasi sto e-commerce me ref sto SessionFactory  
            <bean id="transactionManager"
                class="org.springframework.orm.hibernate4.HibernateTransactionManager">
                <property name="sessionFactory" ref="sessionFactory"></property>
            </bean>
    -->
            <bean id="transactionManager"
                class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <property name="dataSource" ref="dataSource"></property>
            </bean>
            <tx:annotation-driven />
        </beans>

    </beans>

调度-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:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:tx="http://www.springframework.org/schema/tx"
        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-4.1.xsd">

        <context:component-scan base-package="controllers" />

        <mvc:annotation-driven />

        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>

        <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />

        <tx:annotation-driven />
    </beans>

的web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">
        <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>/</url-pattern>
        </servlet-mapping>

        <!-- add listener -->

        <description>eShop Database</description>
        <resource-ref>
            <description>DB Connection</description>
            <res-ref-name>jdbc/myeshop</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>

        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
            WEB-INF/dispatcher-servlet.xml
            WEB-INF/applicationContext.xml
        </param-value>
        </context-param>
        <!-- end of adding listener -->
    </web-app>

的pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

        <modelVersion>4.0.0</modelVersion>
        <groupId>com.mywebsite</groupId>
        <artifactId>emusicstore</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.1.4.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>4.1.1.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>4.1.4.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>4.0.1.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate.javax.persistence</groupId>
                <artifactId>hibernate-jpa-2.0-api</artifactId>
                <version>1.0.1.Final</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>6.0.5</version>
            </dependency>



            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>

            <dependency>
                <groupId>taglibs</groupId>
                <artifactId>standard</artifactId>
                <version>1.1.2</version>
            </dependency>

        </dependencies>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.5.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>        
    </project>

提前致谢! :)

4 个答案:

答案 0 :(得分:0)

的Botas,

您需要将Dao包放在dispatcher-servlet.xml的组件scam标记中。

<context:component-scan base-package="controllers,dao" />

答案 1 :(得分:0)

将applicationContext.xml更改为此

<property name="packagesToScan">
    <list>
        <value>dao.**.*</value>
    </list>
</property>

现在每个班级,即使是在子包装中,都会在春天找到。

答案 2 :(得分:0)

除了包装扫描之外,您似乎错误地定义了sessionFactory。

当您使用spring 4和hibernate 4时,您应将其定义为:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

还尝试将事务管理器定义为:

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <property name="sessionFactory" ref="sessionFactory" />
</bean>

答案 3 :(得分:0)

您正在为应用程序上下文初始化使用批注基础配置,因此必须使用@ComponentScan批注将所有组件加载到dao包中。 @Repository是一个特殊的@Component,用于抽象平台中的数据访问使用异常。