在Controller类中未调用Service Method

时间:2018-01-22 08:30:51

标签: hibernate spring-mvc

这是我的控制器类

  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");



    ApplicationContext context=new ClassPathXmlApplicationContext("hibernate-cfg.xml"); // Line 1
    EmployeeDaoImpl dao= (EmployeeDaoImpl)context.getBean("employeeService"); // Line 2
    dao.addEmployee(emp);  // Line 3


    employeeService.addEmployee(emp);  // Line 4
    } 

}

EmployeeDaoImpl类

package com.kalam.daoimpl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

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

@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {

    private 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();

    }

}

EmployeeServiceImpl代码

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

    }

}

最后是hibernate-cfg.xml文件

<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="mysessionFactory"  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="employeeService" class="com.kalam.daoimpl.EmployeeDaoImpl">    
 <property name="sessionFactory" ref="mysessionFactory" />
 </bean>  



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

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



    </beans>

如果我评论第4行代码和@Autowired EmployeeService employeeService代码并使用第1行到第3行代码,那么它可以正常工作并插入值。但是,当我取消注释@Autowired EmployeeService employeeService和第4行(加上将第1行的行代码注释到第3行)时,我遇到了以下错误。

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

请帮我解决错误。提前谢谢

1 个答案:

答案 0 :(得分:0)

您正在混合注释和xml配置,这本身并不是坏事,但由于混淆而导致覆盖您的一个bean。你在xml中定义了以下内容;

<bean id="employeeService" class="com.kalam.daoimpl.EmployeeDaoImpl">    
    <property name="sessionFactory" ref="mysessionFactory" />
</bean>

当你用服务名称声明dao bean时,这对我没有意义。也许你的意思是employeeDao作为bean id?

无论如何,我的视图中的修复程序是通过简化为java config或xml来清理配置。如果你坚持使用两者而不是将你的xml更改为以下;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 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,com.kalam.serviceimpl,com.kalam.daoimpl,com.kalam.model" />

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

   <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <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>

然后将@Autowired添加到Sessionfactory中的EmployeeDaoImpl,如下所示;

@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {

   @Autowired
   private SessionFactory sessionFactory;

   // Your other methods ...

}

这将确保会话工厂在dao中正确注入,然后在服务器和服务器中为dao注入。