如何使用@Autowired Annotation在Controller中调用服务

时间:2018-01-23 07:31:12

标签: hibernate spring-mvc

这里我试图在spring-hibernate中实现简单的crud操作。为此我已经分离了服务层和Dao层。

EmployeeService接口

package com.kalam.service;

import com.kalam.model.Employee;

public interface EmployeeService {

    public void addEmployee(Employee emp);

    public void updateEmployee(Employee emp);

    public void deleteEmployee(Employee emp,int id);

}

EmployeeDao界面

package com.kalam.dao;

import com.kalam.model.Employee;

public interface EmployeeDao {

public void addEmployee(Employee emp);

    public void updateEmployee(Employee emp);

    public void deleteEmployee(Employee emp,int id);

}

EmployeeServiceImpl类

在这里,我想问一下" @Service(" employeeService")"这一行用id employeeService创建bean吗?

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

    }

}

EmployeeDao class

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

    }

}

最后是最重要的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="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="employeeDaoImpl" class="com.kalam.daoimpl.EmployeeDaoImpl">    
 <property name="sessionFactory" ref="sessionFactory" />
 </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

在这里,我分享了解决问题的方法。

1。我尝试以三种方式更改组件扫描

一个。 <context:component-scan base-package="com.kalam"/>

B中。通过保持所有包装单独扫描:

 <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"/>

℃。通过在一次扫描中合并所有这些:

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

2。我尝试在hibernate-cfg.xml中创建EmployeeServiceImpl的bean,如下所示

 <bean id="employeeDaoImpl"class="com.kalam.serviceimpl.EmployeeServiceImpl">    
         <property name="sessionFactory" ref="sessionFactory" />
  </bean>

按照以下方式注入kalam控制器

@Autowired
EmployeeDaoImpl employeeDaoImpl

第3。此外,我尝试在控制器中注入EmployeeService,而不在hibernate-cfg.xml中为EmployeeService和EmployeeServiceImpl定义bean,如下所示

@Autowired
EmployeeService employeeService 

4。我最后一个重要的疑问是&#34; @Service(&#34; employeeService&#34;)&#34; EmployeeServiceImpl中的代码创建一个bean?以便我们可以使用

@Autowired
EmployeeService employeeService 

在控制器类中调用控制器类中的服务方法。在这里,我再一次强调了我将服务和dao层分开的观点。

告诉我如何启用@Autowired     EmployeeService employeeService直接进入控制器类。我知道我试图混合xml和注释方法。由于我浪费了大量时间来解决这个错误,因此我非常紧张。请帮我。谢谢。谢谢。

0 个答案:

没有答案