2016-11-13 27 views
1

我已经经历了这个话题的每一篇文章,但我仍然无法找到什么是错的。当我尝试运行服务器我得到这个异常:Spring + Hibernate。创建bean时出错。不满意的依赖。不知道什么注释是不对的

org.springframework.beans.factory.UnsatisfiedDependencyException: 错误名为“administratorDAO”创建豆:不满意 依赖过法“setDao”参数0表示:否 为[依赖关系] [com.project.dataAccessLayer.DataAccessObject]: 找到类型为[com.project.dataAccessLayer.DataAccessObject]的合格bean的 ,期望至少1个符合此依赖关系的自动装填候选资格的bean。依赖注释:{};嵌套的异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:无类型[com.project.dataAccessLayer.DataAccessObject] 的 排位豆找到的依赖性[com.project.dataAccessLayer.DataAccessObject]: 预期至少1豆,其有资格作为 此依赖关系的自动导向候选。依赖注解:{}

它说,我没有豆的DataAccessObject即使它与@Repository注解或也servlet的context.xml中定义

我有一个CustomerDAO和延伸CustomerDAO的AdministratorDAO 。我只会发布客户部分,因为我认为如果我能做到这一点,管理员部分将会遵循。

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> 

根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和服务豆,因为我理解@Repository,@Component和@服务注释将创建bean。

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

enter image description here

+0

你应该分开文件的内容,仔细格式化。 –

+1

我刚刚完成编辑后,现在是可读的,对不起 – Bomfly

回答

0

你期待的依赖DataAccessObject豆与@Qualifier("custDAO")CustomerDAO内,但没有DataAccessObject豆可用@Qualifier("custDAO")

换句话说,这个问题是因为@Qualifier("custDAO")即,Spring容器不能注入DataAccessObject豆到CustomerDAO(因为有可与预期@Qualifier NO豆),所以你需要改变你的DataAccessObject如下图所示:

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

你可以看看here更多关于@Qualifier

+0

我也有@Repository的AdministratorDAO类(“administratorDAO”) 公共类AdministratorDAO扩展CustomerDAO实现IAdministratorDAO { \t \t DataAccessObject道; \t @Autowired \t @Qualifier( “adminDAO”) \t公共无效setDao(DataAccessObject DAO){ \t \t this.dao =道; \t}所以我添加了限定符,因为另一个错误,说我有两个“道”豆 – Bomfly

+0

如果我这样做,我将如何能够在AdministratorDAO中使用DataAccessObject? – Bomfly

+0

确保无论您拥有一个用于setter注入(或注入)的限定符,您都有一个具有Qualifier注解的具体类(实现)。 – developer

相关问题