2017-04-11 157 views
0

我無法讓我的應用程序工作。我已經嘗試了幾乎所有的東西,包括在多個地方添加@Transactional註解,但似乎沒有任何工作。@EnableTransactionManagement導致應用程序失敗

當我使用openSession或hibernateTemplate時,它工作正常。當我將它們作爲JUnit測試運行時,它也可以正常工作,但在運行Web應用程序時不起作用。

下面是我的pom.xml的版本:

<properties> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    <spring.version>4.2.2.RELEASE</spring.version> 
    <installed.version>1.0</installed.version> 
    <slf4j.version>1.7.5</slf4j.version> 
    <spring.ldap.version>2.0.2.RELEASE</spring.ldap.version> 
    <jackson.library>2.7.5</jackson.library> 
    <hibernate.version>5.0.2.Final</hibernate.version> 
</properties> 

這裏是我的代碼:

DAO實現:

package com.pkim.crud.dao; 

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

import org.apache.commons.lang3.StringUtils; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.orm.hibernate5.HibernateTemplate; 
import org.springframework.stereotype.Repository; 
import org.springframework.transaction.annotation.Transactional; 

import com.pkim.crud.model.Crud; 

@Repository("crudHibernateDao") 
@Transactional 
public class CrudDaoHibernateImpl implements CrudDao 
{ 
    @Autowired 
    private SessionFactory sessionFactory; 

    @Override 
    public List<Crud> getCruds() 
    { 

     Session session = this.sessionFactory.getCurrentSession(); 
     List<Crud> crudList = (List<Crud>)session.createQuery("from Crud").list(); 

     return crudList; 
    } 
} 

MODEL:

package com.pkim.crud.model; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.Id; 
import javax.persistence.Table; 
import javax.xml.bind.annotation.XmlRootElement; 

import org.apache.commons.lang3.StringUtils; 
@Entity 
@Table(name="crud") 
@XmlRootElement 
public class Crud 
{ 
    @Id 
    @Column(name="id") 
    private Long id; 

    @Column(name = "description", nullable = false) 
    private String description; 

    public Crud() 
    { 
     this.setId(null); 
     this.setDescription(StringUtils.EMPTY); 
    } 

    public Long getId() 

     return id; 
    } 
    public void setId(Long id) 
    { 
     this.id = id; 
    } 
    public String getDescription() 
    { 
     return description; 
    } 
    public void setDescription(String description) 
    { 
     this.description = description; 
    } 
} 

JAVA配置:

package com.pkim.crud.config; 

import java.util.Properties; 

import javax.sql.DataSource; 

import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.MessageSource; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.context.annotation.PropertySource; 
import org.springframework.context.support.ResourceBundleMessageSource; 
import org.springframework.core.env.Environment; 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 
import org.springframework.orm.hibernate5.HibernateTransactionManager; 
import org.springframework.orm.hibernate5.LocalSessionFactoryBean; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 
import org.springframework.web.servlet.view.InternalResourceViewResolver; 
import org.springframework.web.servlet.view.JstlView; 
import org.springframework.transaction.annotation.EnableTransactionManagement 
import com.pkim.crud.helper.Constants; 

@Configuration 
@ComponentScan(basePackages = { Constants.PACKAGE_TO_SCAN }) 
@PropertySource({ "classpath:config.properties" }) 
@EnableWebMvc 
@EnableTransactionManagement 

public class Config 
{ 
    @Autowired 
    private Environment environment; 

    @Bean 
    public DataSource dataSource() 
    { 
     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName(environment.getProperty("db.driverClassName")); 
     dataSource.setUrl(environment.getProperty("db.url")); 
     dataSource.setUsername(environment.getProperty("db.username")); 
     dataSource.setPassword(environment.getProperty("db.password")); 

     return dataSource; 
    } 


    @Bean 
    public InternalResourceViewResolver viewResolver() 
    { 
     InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 
     viewResolver.setViewClass(JstlView.class); 
     viewResolver.setPrefix("/jsp/"); 
     viewResolver.setSuffix(".jsp"); 

     return viewResolver; 
    } 

    @Bean 
    public MessageSource messageSource() 
    { 
     ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); 
     messageSource.setBasenames("messages"); 
     messageSource.setDefaultEncoding("UTF-8"); 

     return messageSource; 
    } 

    public void addResourceHandlers(final ResourceHandlerRegistry registry) 
    { 
     registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
    } 


    @Bean 
    public LocalSessionFactoryBean sessionFactory() 
    { 
     LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 
     sessionFactory.setDataSource(this.dataSource()); 
     sessionFactory.setPackagesToScan(new String[] { Constants.PACKAGE_TO_SCAN }); 
     sessionFactory.setHibernateProperties(hibernateProperties()); 

     return sessionFactory; 
    } 


    private Properties hibernateProperties() 
    { 
     Properties properties = new Properties(); 

     properties.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("hibernate.hbm2ddl.auto")); 
     properties.setProperty("hibernate.dialect", environment.getProperty("hibernate.dialect")); 
     properties.setProperty("hibernate.globally_quoted_identifiers", "true"); 

     return properties; 
    } 

    @Bean 
    @Autowired 
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) 
    { 
     HibernateTransactionManager txManager = new HibernateTransactionManager(); 
     txManager.setSessionFactory(sessionFactory); 

     return txManager; 
    } 
} 

錯誤消息:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]: Factory method 'transactionAdvisor' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionInterceptor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'transactionManager' is required 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:201) 
    at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:240) 
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:683) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:522) 
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446) 
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328) 
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) 
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4725) 
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189) 
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) 
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419) 
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) 
    at java.util.concurrent.FutureTask.run(Unknown Source) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) 
    at java.lang.Thread.run(Unknown Source) 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]: Factory method 'transactionAdvisor' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionInterceptor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'transactionManager' is required 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:201) 
    at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92) 
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:101) 
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:87) 
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:69) 
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:330) 
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:293) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) 
    ... 20 more 
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]: Factory method 'transactionAdvisor' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionInterceptor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'transactionManager' is required 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) 
    ... 37 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionInterceptor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'transactionManager' is required 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) 
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) 
    at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c78190b2.transactionInterceptor(<generated>) 
    at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.transactionAdvisor(ProxyTransactionManagementConfiguration.java:45) 
    at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c78190b2.CGLIB$transactionAdvisor$0(<generated>) 
    at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c78190b2$$FastClassBySpringCGLIB$$d400c72.invoke(<generated>) 
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) 
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318) 
    at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c78190b2.transactionAdvisor(<generated>) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) 
    ... 38 more 
Caused by: java.lang.IllegalArgumentException: Property 'transactionManager' is required 
    at org.springframework.transaction.interceptor.TransactionAspectSupport.afterPropertiesSet(TransactionAspectSupport.java:195) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) 
    ... 57 more 
+0

確保你不混合版本。 – sura2k

+0

我使用Spring 4.2.2.RELEASE和Hibernate 5.0.2.Final。我試着從示例中降級到早期版本,但我仍然得到相同的錯誤。 – Pat

+0

當我刪除@EnableTransactionManagement註釋時,它可以工作,但是我必須明確地管理我的會話。我還必須設置以下hibernate屬性:properties.setProperty(「hibernate.current_session_context_class」,「thread」);否則我會得到另一個錯誤。 – Pat

回答

0

我覺得這是你的依賴問題。檢查你的彈簧上下文依賴關係

+0

所有的Spring依賴項都是4.2.2.RELEASE。 – Pat

+0

我建議你嘗試在模型類中加入默認構造函數。並讓我知道如果它的工作.. –

相關問題