Spring + Hibernate的。创建bean时出错。不满意的依赖。无法弄清楚注释不正确

时间:2016-11-13 01:31:30

标签: java spring hibernate spring-mvc

我已经完成了关于这个主题的每一篇文章,但我仍然找不到什么问题。当我尝试运行服务器时,我得到了这个例外:

  

org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名为“administratorDAO”的bean时出错:不满意   通过方法'setDao'参数0表示的依赖关系:否   [com.project.dataAccessLayer.DataAccessObject]类型的限定bean   找到依赖项[com.project.dataAccessLayer.DataAccessObject]:   预计至少有1个豆有资格成为autowire候选人   这种依赖。依赖注释:{};嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   [com.project.dataAccessLayer.DataAccessObject]类型的限定bean   找到依赖项[com.project.dataAccessLayer.DataAccessObject]:   预计至少有1个豆有资格成为autowire候选人   这种依赖。依赖注释:{}

它表示我没有DataAccessObject的bean,即使它是用@Repository注释的,也是在servlet-context.xml中定义的

我有一个CustomerDAO和一个AdministratorDAO,它扩展了CustomerDAO。我将仅发布客户部分,因为我认为如果我可以完成这项工作,管理员部分将会跟进。

DataAccessObject class

package com.project.dataAccessLayer;

import java.util.List;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.project.model.Account;
import com.project.model.ModelEntity;
import com.project.model.Product;


@Repository("dao")
public class DataAccessObject {


    private SessionFactory sessionFactory;
    private Session session;

    @Autowired
    @Qualifier("sessionFactory")
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public ModelEntity save(ModelEntity modelEntity) {
        Integer id = null;
        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            id = (Integer) session.save(modelEntity);
            if (id != null) {
                modelEntity.setId(id);
            }
            session.getTransaction().commit();
            session.close();

        } catch (Exception e) {
            this.update(modelEntity);
        }

        return modelEntity;

    }


    public void update(ModelEntity modelEntity) {
        try {

            session = sessionFactory.openSession();
            session.beginTransaction();

            session.update(modelEntity);

            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }

    }

    @SuppressWarnings("unchecked")
    public List<Product> getProducts() {
        List<Product> list = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();

            list = session.createCriteria(Product.class).list();

            session.getTransaction().commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }

        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Account> getAccounts() {
        List<Account> list = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();

            list = session.createCriteria(Account.class).list();

            session.getTransaction().commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }

        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Product> getProductByName(String brand, String model) {
        List<Product> list = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();

            list = session.createCriteria(Product.class).add(Restrictions.eq("brand", brand))
                    .add(Restrictions.eq("model", model)).list();

            session.getTransaction().commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }

        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Account> getAccountByUsername(String username) {
        List<Account> list = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();

            list = session.createCriteria(Account.class).add(Restrictions.eq("username", username)).list();

            session.getTransaction().commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }

        return list;
    }

    public void delete(ModelEntity modelEntity) {
        try {

            session = sessionFactory.openSession();
            session.beginTransaction();

            session.delete(modelEntity);

            session.getTransaction().commit();
            session.clear();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }


    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }


}

CustomerDAO类

package com.project.dataAccessLayer;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.project.model.Account;
import com.project.model.Permission;
import com.project.model.Product;


@Repository("customerDAO")
public class CustomerDAO implements ICustomerDAO {


    DataAccessObject dao;

    @Autowired
    @Qualifier("custDAO")
    public void setDao(DataAccessObject dao) {
        this.dao = dao;
    }

    public DataAccessObject getDao() {
        return dao;
    }


    public Account signUp(String fullName, String username, String password, String email, String address,
            Permission permission) throws Exception {

        List<Account> allAccounts = dao.getAccounts();
        for (Account it : allAccounts) {
            if (it.getUsername().equals(username)) {
                throw new Exception("The username already exists");
            }
        }
        Account newAccount = new Account(fullName, username, password, email, address, permission);
        Account savedAccount = (Account) dao.save(newAccount);
        return savedAccount;
    }


    public int logIn(String username, String password) throws Exception {

        List<Account> allAccounts = dao.getAccounts();
        for (Account it : allAccounts) {
            if (it.getUsername().equals(username)) {
                {
                    if (it.getPassword().equals(password)) {
                        if (it.isOnline() == false) {
                            it.setOnline(true);
                            dao.update(it);
                            return 200;
                        } else {
                            throw new Exception("You are already logged in");
                        }
                    } else {
                        throw new Exception("Invalid password");
                    }
                }
            }
        }
        // The username was not found in the database
        return 404;
    }

    public int logOut(int accountId) throws Exception {
        List<Account> allAccounts = dao.getAccounts();
        for (Account it : allAccounts) {
            if (it.getId() == accountId) {
                {
                    if (it.isOnline()) {
                        it.setOnline(false);
                        dao.update(it);
                        return 200;
                    } else {
                        throw new Exception("You are not logged in");
                    }
                }
            }
        }

        return 400;
    }


    public Account changePassword(String username, String oldPassword, String newPassword) throws Exception {
        List<Account> allAccounts = dao.getAccounts();
        for (Account it : allAccounts) {
            if (it.getUsername().equals(username)) {
                {
                    if (it.getPassword().equals(oldPassword)) {
                        if (it.isOnline()) {
                            it.setPassword(newPassword);
                            dao.update(it);
                            return it;
                        } else {
                            throw new Exception("You must be logged in in order to change password");
                        }
                    } else {
                        throw new Exception("Invalid password");
                    }
                }
            }
        }
        return null;
    }


    public List<Product> showAllProducts() {
        return dao.getProducts();
    }


    public List<Product> getProductByName(String brand, String model) {
        return dao.getProductByName(brand, model);
    }


}

CustomerService类

package com.project.services;

import java.util.List;

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

import com.project.dataAccessLayer.CustomerDAO;
import com.project.model.Account;
import com.project.model.Permission;
import com.project.model.Product;

@Service("customerService")
@Transactional
public class CustomerService implements ICustomerService {


    private CustomerDAO cDAO;

    public CustomerDAO getcDAO() {
        return cDAO;
    }

    @Autowired
    public void setcDAO(CustomerDAO cDAO) {
        this.cDAO = cDAO;
    }

    @Transactional
    public Account signUp(String fullName, String username, String password, String email, String address,
            Permission permission) throws Exception {

        if (username.equals("") || password.length() < 3 || permission == null) {

            throw new Exception("You must provide a username and a minimum 3 character long password");
        } else {
            return cDAO.signUp(fullName, username, password, email, address, permission);
        }

    }

    @Transactional
    public boolean logIn(String username, String password) throws Exception {

        if (cDAO.logIn(username, password) == 200)
            return true;

        return false;
    }

    @Transactional
    public boolean logOut(int accountId) throws Exception {

        if (cDAO.logOut(accountId) == 200)
            return true;
        return false;
    }

    @Transactional
    public Account changePassword(String username, String oldPassword, String newPassword) throws Exception {

        if (newPassword.length() < 3) {
            throw new Exception("Password must have minimum 3 characters");
        }

        return cDAO.changePassword(username, oldPassword, newPassword);
    }

    @Transactional
    public List<Product> showAllProducts() {
        return cDAO.showAllProducts();
    }

    @Transactional
    public Product getProductByName(String brand, String model) throws Exception {

        List<Product> pList = cDAO.getProductByName(brand, model);
        if (pList.isEmpty()) {
            throw new Exception(brand + " " + model + " does not exist");
        } else {
            return pList.get(0);
        }
    }

}

CustomerController类

package com.project.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
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 org.springframework.web.servlet.ModelAndView;

import com.project.model.Account;
import com.project.model.Product;
import com.project.services.CustomerService;
import com.project.services.ICustomerService;

@Controller("customerCOntroller")
@RequestMapping("/")
public class CustomerController {

    ICustomerService customerService;

    @Autowired(required = true)
    @Qualifier(value="customerService")
    public void setCustomerService(CustomerService cs){
        this.customerService = cs;
    }

    @RequestMapping(value = "/account", method = RequestMethod.GET)
    public ModelAndView showForm() {
        return new ModelAndView("account", "account", new Account());
    }

    @RequestMapping(value = "/signUp", method = RequestMethod.POST)
    public String signUp(@ModelAttribute("account") Account acc) throws Exception {

        this.customerService.signUp(acc.getFullName(), acc.getUsername(), acc.getPassword(), acc.geteMail(),
                acc.getAddress(), acc.getPermission());

        return "redirect:/logIn";

    }

    @RequestMapping(value = "/logIn", method = RequestMethod.POST)
    public String logIn(@ModelAttribute("account") Account acc) throws Exception {

        this.customerService.logIn(acc.getUsername(), acc.getPassword());

        return "redirect:/products";
    }

    @RequestMapping(value = "/logOut", method = RequestMethod.POST)
    public String logOut(@ModelAttribute("account") Account acc) throws Exception {

        this.customerService.logOut(acc.getId());

        return "redirect:/logIn";
    }

    @RequestMapping(value="/changePassword/{newPassword}",  method = RequestMethod.POST)
    public String changePassword(@ModelAttribute("account") Account acc,
            @PathVariable("newPassword") String newPassword) throws Exception {
        this.customerService.changePassword(acc.getUsername(), acc.getPassword(), newPassword);
        return "redirect:/logIn";
    }

    @RequestMapping(value = "/products", method = RequestMethod.GET)
    public ModelAndView showProducts() {
        List<Product> productList = this.customerService.showAllProducts();
        return new ModelAndView("products", "productList", productList);
    }
}

web.xml

 <....>``



    <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/root-context.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>/WEB-INF/appServlet/servlet-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>

root-context.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"
        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">

    </beans>

servlet的context.xml中

    <?xml ....">

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

        <context:component-scan base-package="com.project" />

        <!-- Enables the Spring MVC @Controller programming model -->
        <annotation-driven />

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


        <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <beans:property name="url"
                value="jdbc:mysql://localhost:3306/guitarshop" />
            <beans:property name="username" value="root" />
            <beans:property name="password" value="" />
        </beans:bean>


        <beans:bean id="sessionFactory"
            class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <beans:property name="annotatedClasses">
                <beans:list>
                    <beans:value>com.project.model.Account</beans:value>
                    <beans:value>com.project.model.Product</beans:value>
                </beans:list>
            </beans:property>
            <beans:property name="hibernateProperties">
                <beans:props>
                    <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                    </beans:prop>
                    <beans:prop key="hibernate.show_sql">true</beans:prop>
                    <beans:prop key="hibernate.enable_lazy_load_no_trans">true</beans:prop>
                </beans:props>
            </beans:property>
        </beans:bean>

    <!--    <beans:bean id="dao" -->
    <!--        class="com.project.dataAccessLayer.DataAccessObject"> -->
    <!--        <beans:property name="sessionFactory" ref="sessionFactory" /> -->
    <!--    </beans:bean> -->

    <!--    <beans:bean id="customerDAO" class="com.project.dataAccessLayer.CustomerDAO"> -->
    <!--        <beans:property name="dao" ref="dao" /> -->
    <!--    </beans:bean> -->

    <!--    <beans:bean id="administratorDAO" -->
    <!--        class="com.project.dataAccessLayer.AdministratorDAO"> -->
    <!--        <beans:property name="dao" ref="dao" /> -->
    <!--    </beans:bean> -->


    <!--    <beans:bean id="customerService" class="com.project.services.CustomerService"> -->
    <!--        <beans:property name="customerDAO" ref="customerDAO"></beans:property> -->
    <!--    </beans:bean> -->

    <!--    <beans:bean id="administratorService" class="com.project.services.AdministratorService"> -->
    <!--        <beans:property name="administratorDAO" ref="administratorDAO"></beans:property> -->
    <!--    </beans:bean> -->

        <tx:annotation-driven transaction-manager="transactionManager" />

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

    </beans:beans>

我评论了DAO和Service bean,因为我知道@ Repository,@ Component和@Service注释将创建bean。

我必须在CustomerDAO和AdministratorDAO中使用DataAccessObject。

enter image description here

1 个答案:

答案 0 :(得分:0)

您希望DataAccessObject中包含@Qualifier("custDAO")CustomerDAO个bean,但DataAccessObject

没有@Qualifier("custDAO")个bean

换句话说,问题是因为@Qualifier("custDAO") ie,Spring容器无法将DataAccessObject bean注入CustomerDAO(因为没有可用的bean)对于预期的@Qualifier),您需要更改DataAccessObject,如下所示:

@Repository
@Qualifier("custDAO")
public class DataAccessObject {
    //current code
}

您可以在@Qualifier

上查看here了解更多信息