自动装配失败,Bean创建错误

时间:2018-01-22 13:40:49

标签: hibernate spring-mvc

我正在尝试使用Spring-Hibernate实现简单的CRUD操作。

这是我的EmployeeServieImpl文件

package com.kalam.serviceimpl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.kalam.dao.EmployeeDao;
import com.kalam.daoimpl.EmployeeDaoImpl;
import com.kalam.model.Employee;
import com.kalam.service.EmployeeService;

@Service("employeeService")
@Transactional(propagation=Propagation.SUPPORTS,rollbackFor=Exception.class)
public class EmployeeServiceImpl implements EmployeeService{


    @Autowired
    EmployeeDao employeeDao;

    public void addEmployee(Employee emp) {
        employeeDao.addEmployee(emp);

    }

    public void updateEmployee(Employee emp) {
        // TODO Auto-generated method stub

    }

    public void deleteEmployee(Employee emp, int id) {
        // TODO Auto-generated method stub

    }

}

EmployeeDaoImpl类

package com.kalam.daoimpl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kalam.dao.EmployeeDao;
import com.kalam.model.Employee;

@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
    @Autowired
     SessionFactory sessionFactory;


    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }



    public void addEmployee(Employee emp) {
        Session session = sessionFactory.openSession();
        Transaction tx= session.beginTransaction();
        session.save(emp);
        tx.commit();
        session.close();
    }



    public void updateEmployee(Employee emp) {
         Session session = sessionFactory.getCurrentSession();
          session.beginTransaction();
            session.update(emp);
            session.getTransaction().commit();

    }



    public void deleteEmployee(Employee emp, int id) {
         Session session = this.sessionFactory.getCurrentSession();
          session.beginTransaction();
            Employee employee = (Employee) session.get(Employee.class, new Integer(id));
            if(null != employee){
                session.delete(emp);
                                }
       session.getTransaction().commit();

    }

}

控制器文件

package com.kalam.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kalam.daoimpl.EmployeeDaoImpl;
import com.kalam.model.Employee;
import com.kalam.service.EmployeeService;



@Controller
@RequestMapping("/hello")
public class KalamController {

@Autowired
EmployeeService employeeService;

    @RequestMapping("/kalam")
    public String showMessage(ModelMap map) {

        map.put("dollar", "50 US $");
        return "KalamWorld";
    }

    @RequestMapping(value="/insertData",method=RequestMethod.GET)
    public void InserData() {

        Employee emp= new Employee();
        emp.setEmpID(11);
        emp.setEmpName("On Target");
        emp.setEmpSalary(20000);
        emp.setAddress("Mumbai");


        employeeService.addEmployee(emp);  
    } 

}

最后是hibernate配置类。

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"  
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 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-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- Activate Spring annotation support -->
<context:annotation-config />

<mvc:annotation-driven /> 

<context:component-scan base-package="com.kalam.controller" />
<context:component-scan base-package="com.kalam.serviceimpl"/>
<context:component-scan base-package="com.kalam.daoimpl"/>
<context:component-scan base-package="com.kalam.model"/>

<!-- DataSource configurationt -->
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>  
        <property name="url" value="jdbc:mysql://localhost:3306/kalamdb"></property>  
        <property name="username" value="root"></property>  
        <property name="password" value="root"></property>  
    </bean>  

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

        <property name="mappingResources">  
        <list>  
        <value>employee.hbm.xml</value>  
        </list>  
        </property>  

        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.show_sql">true</prop>  
            </props>  
        </property>  
    </bean>





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

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



    </beans>  

当我运行该程序时,我收到以下错误。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kalamController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.kalam.service.EmployeeService com.kalam.controller.KalamController.employeeService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.kalam.service.EmployeeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5110)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5633)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1694)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1684)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.kalam.service.EmployeeService com.kalam.controller.KalamController.employeeService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.kalam.service.EmployeeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.kalam.service.EmployeeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 24 more

请告诉我为什么我会收到这样的错误。您也可以通过示例告诉我xml和annotaion配置之间的区别。请提供任何有用的链接或内容。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您没有将EmployeeService定义为Spring bean(标记为@Component@Service,....)。

似乎你应该尝试在控制器内(或任何你需要的地方)而不是EmployeeServiceImpl注入EmployeeService。 要么 在此发布您的EmployeeService,了解我们可以做些什么。

也许如果您将<context:component-scan base-package="com.kalam.controller" />替换为<context:component-scan base-package="com.kalam.*" />并删除其他<context:component-scan>,您就可以了。 (也许你的界面在另一个你没有添加到组件扫描的包中)。