简体   繁体   中英

Spring+Hibernate. Error creating bean. Unsatisfied dependency. Cannot figure out what annotation is not right

I've gone through every post on this topic but I still can't find what's wrong. When I try to run the server I get this exception:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'administratorDAO': Unsatisfied dependency expressed through method 'setDao' parameter 0: No qualifying bean of type [com.project.dataAccessLayer.DataAccessObject] found for dependency [com.project.dataAccessLayer.DataAccessObject]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.project.dataAccessLayer.DataAccessObject] found for dependency [com.project.dataAccessLayer.DataAccessObject]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

It says that I have no bean for DataAccessObject even if it's annotated with @Repository or also defined in servlet-context.xml

I have a CustomerDAO and an AdministratorDAO which extends CustomerDAO. I'll post only the customer part as I think that if I can make that work, the administrator part will follow.

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 class

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 class

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 class

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 (empty)

    <?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>

I commented the DAO and Service beans because i understood that @Repository, @Component and @Service annotations will create the beans.

I have to use DataAccessObject in both CustomerDAO and AdministratorDAO.

在此输入图像描述

You are expecting a dependency DataAccessObject bean with @Qualifier("custDAO") inside your CustomerDAO , but there are NO DataAccessObject beans available with @Qualifier("custDAO")

In other words, the issue is because of the @Qualifier("custDAO") ie, Spring container could NOT inject the DataAccessObject bean into the CustomerDAO (as there are NO beans available with the expected @Qualifier ), so you need to change your DataAccessObject as shown below:

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

You can look here for more on @Qualifier

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM