使用事务时在bean上获取BeanCreationException

时间:2013-09-25 17:27:30

标签: java spring hibernate spring-mvc transactions

我有一个bean,它基本上是一个使用@Transactional注释进行事务处理的服务。我正在使用hibernate,这里是applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db"/>
        <property name="user" value="username"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.myprojects.User</value>
            </list>
        </property>
    </bean>

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

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

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

    <bean id="userService" class="com.myprojects.service">
        <property name="template" ref="hibernateTemplate"/>
    </bean>

</beans>

我是Spring和hibernate的新手,当我浏览spring transaction management here的文档时,我尝试实现一个简单的基于事务的bean,就像上面的例子一样,但在部署它时,我得到了beancreationexception。我错过了任何配置吗?

堆栈追踪:

  

2013年9月29日下午9:25:29 org.apache.catalina.core.StandardContext loadOnStartup   严重:Servlet / myWorld抛出了load()异常   org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到类型为[com.myprojects.myworld.daoimpl.UsersDAOImpl]的限定bean依赖:预期至少有1个bean符合此依赖关系的autowire候选者。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}       at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)       at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)       在org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)       at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)       在org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)       at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)       at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:295)       在org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)       在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)       在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)       at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)       在org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)       在org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)       在org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)       在org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)       在org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)       在org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)       在org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)       在org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)       在javax.servlet.GenericServlet.init(GenericServlet.java:212)       在org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1213)       在org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)       at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)       在org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)       在org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)       在org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)       在org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)       在org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943)       在org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:563)       在org.apache.catalina.startup.HostConfig.check(HostConfig.java:1399)       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)       at java.lang.reflect.Method.invoke(Method.java:606)       at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:297)       at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)       at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)       在org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1500)       在org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:670)       在org.apache.catalina.manager.ManagerServlet.doPut(ManagerServlet.java:435)       在javax.servlet.http.HttpServlet.service(HttpServlet.java:646)       在javax.servlet.http.HttpServlet.service(HttpServlet.java:723)       在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)       在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)       在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)       at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)       at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:563)       在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)       在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)       在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)       在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)       在org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)       在org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler.process(Http11Protocol.java:606)       在org.apache.tomcat.util.net.JIoEndpoint $ Worker.run(JIoEndpoint.java:489)       在java.lang.Thread.run(Thread.java:724)

我有一个自动装配服务的控制器:

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private service s;

    //few methods like getUser/postUser are written here
}

服务:

@Transactional
public class service {
    private HibernateTemplate template;
    public void updateUser(User u) {
        Session session = template.getSessionFactory().getCurrentSession();
        u.update(session);
    }
}

用户类:

public class User {
    public void updateUser(Session session) {
        Transaction tx = session.beginTransaction();
        try {
           //carry out update user
        } catch(Exception e) {
           tx.rollback();
        } finally {
           session.close();
        }
    }
}

Hibernate配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.current_session_context_class">thread</property>
  </session-factory>
</hibernate-configuration>

myproject-servlet.xml:

<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:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
       xmlns:tx="http://www.springframework.org/schema/tx">

    <context:component-scan base-package="com.myprojects"/>

    <context:annotation-config/> 
    <tx:annotation-driven/>
    <mvc:annotation-driven/>

</beans>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>contextConfiguration</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>myproject</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/myproject-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>myproject</servlet-name>
        <url-pattern>/v1/*</url-pattern>
    </servlet-mapping>

</web-app>

1 个答案:

答案 0 :(得分:1)

由于您的service是具体类(不是接口),因此您可以将属性proxy-target-class="true"添加到<tx:annotation-driven transaction-manager="transactionManager"/>

或者创建一个接口(其中service可以是具体的实现)并使用该接口进行自动装配/注入。

参考:Spring Transaction Docs

请注意,在设置proxy-target-class="true"时,请务必在具体类上保留@Transactional注释。上面引用的Spring文档中有关于该点的更多信息,以及应放置@Transactional注释的位置。