:java.lang.IllegalArgumentException:属性'transactionManager'是必需的

时间:2017-02-23 08:40:31

标签: java spring hibernate

这个问题已经被问到了。但我没有得到适合我的方案的解决方案。我使用的是spring-orm 4.1.6和hibernate-core 4.3.11。

错误日志:

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanConfig': 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:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at com.hex.test.TestClient.main(TestClient.java:14)
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:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
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)
... 10 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)
... 27 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:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:322)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$78661ecf.transactionInterceptor(<generated>)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.transactionAdvisor(ProxyTransactionManagementConfiguration.java:45)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$78661ecf.CGLIB$transactionAdvisor$0(<generated>)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$78661ecf$$FastClassBySpringCGLIB$$644c79f6.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$78661ecf.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)
... 28 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)
... 47 more

我的实体班 -

package com.hex.vo;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Table;
import org.hibernate.annotations.*;

/**
  * The Author is a entity class which represents 
  * the author table. 
 */
@Entity

@Table(name="Author")
public class Author implements Serializable   {

/** The authorID which represents authorID column in the table. */

@Id
@Columns(columns = { @Column(name="authorID",insertable=true,updatable=true,length=10) })
private Integer authorID;

/**
 * Sets the authorID.
 *
 * @param newValue- the new authorID
 */
public void setAuthorID(Integer newValue) { 
    authorID = newValue; 
}

/**
 * Gets the authorID.
 *
 * @return the authorID
 */
public Integer getAuthorID() { 
    return authorID;
}


/** The name which represents name column in the table. */

@Columns(columns = { @Column(name="name",insertable=true,updatable=true,length=45) })
private String name;

/**
 * Sets the name.
 *
 * @param newValue- the new name
 */
public void setName(String newValue) { 
    name = newValue; 
}

/**
 * Gets the name.
 *
 * @return the name
 */
public String getName() { 
    return name;
}



/* (non-Javadoc)
 * @see java.lang.Object#equals(java.lang.Object)
 */
public boolean equals(Object object) {
    if (object instanceof Author) {
        Author pk = (Author)object;
        if ((pk.authorID == null )) {
            return name.equals(pk.getName());
         } else 
        return authorID.equals(pk.getAuthorID())&&name.equals(pk.getName());
    } else {
        return false;
    }
}

/* (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
public int hashCode() {
    if (authorID == null ) {
        return (name !=null ?name.hashCode():0);
     } else         
    return (authorID !=null ?authorID.hashCode():0)+(name !=null ?name.hashCode():0);
}

}

我的BaseDAO课程 -

package com.hex.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hex.exceptions.ValidationException;


@Component
public class BaseDAO {

Logger log= Logger.getLogger("BaseDAO");

@Autowired
HibernateTemplate hibernateTemplate;

public HibernateTemplate getHibernateTemplate() {
    return hibernateTemplate;
}

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
    this.hibernateTemplate = hibernateTemplate;
}

/**
 * <b> insert </b> method inserts a new object in to the database.
 * 
 * @param object-
 *            name of entity
 */
@Transactional
public void insert(Object object) {
    log.info("Inside insert method..");
    try {
        if (!validateObject(object)) {
            hibernateTemplate.save(object);
        }
        log.info("object inserted successfully");
    } catch (ValidationException e) {
        e.printStackTrace();
    }
}


/**
 * <b> select </b> method finds the object from the database.
 * 
 * @param clazz
 *            - Entity class
 * @param primaryKey
 *            -PrimarKey of the entity to be found
 * @return Object - Entity object
 * @return-selected object
 */
public Object select(Class clazz, Object primaryKey) {
    Object result = hibernateTemplate.get(clazz, (Serializable) primaryKey);
    return result;

}
 /**
 * <b> validateObject </b> method validates the Entity object against the
 * specified validation constraints.
 * 
 * @param object
 *            - Object to be validate
 * @return boolean -returns the boolean value according to the validation of
 *         the object
 * @throws ValidationException
 */
private boolean validateObject(Object object) throws ValidationException {
    log.info("Inside validateObject method..");
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Object>> constraintViolations = null;
    constraintViolations = validator.validate(object);
    if (constraintViolations.size() > 0) {
        StringBuffer error = new StringBuffer();
        Iterator<ConstraintViolation<Object>> iterator = constraintViolations.iterator();
        while (iterator.hasNext()) {
            ConstraintViolation<Object> constraintviolation = iterator.next();
            String constraintsMessage = constraintviolation.getMessage();
            javax.validation.Path columnName = constraintviolation.getPropertyPath();
            error.append(columnName.toString() + "--->" + constraintsMessage);
        }
        log.severe(error.toString());
        throw new ValidationException(error.toString());
    } else {
        return false;
    }
}

}

我的BeanConfig类 -

package com.hex.util;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration

@EnableTransactionManagement

public class BeanConfig {

@Bean
public HibernateTemplate getHibTemplate(SessionFactory sessionFactory) {
    HibernateTemplate hibernateTemplate = new HibernateTemplate();
    hibernateTemplate.setSessionFactory(sessionFactory);
    return hibernateTemplate;
}

@Bean
public BaseDAO getAuthorDao() {
    return new BaseDAO();
}

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(getdatDataSource());
    sessionFactory.setPackagesToScan("com.hex.vo");
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource getdatDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/test");
    ds.setUsername("root");
    ds.setPassword("admin");
    return ds;
}

Properties hibernateProperties() {
    return new Properties() {
        private static final long serialVersionUID = 1L;

        {
            setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
            setProperty("hibernate.hbm2ddl.auto", "update");
            setProperty("hibernate.show_sql", "true");
            setProperty("current_session_context_class", "thread");
            setProperty("cache.provider_class", "org.hibernate.cache.NoCacheProvider");
            setProperty("connection.pool_size", "1");
        }
    };
}

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

}

主类 -

package com.hex.test;

import com.hex.vo.Author;

import com.hex.util.BaseDAO;
import com.hex.util.BeanConfig;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestClient {

 public static void main(String[] arg) {
    AbstractApplicationContext context = new   AnnotationConfigApplicationContext(BeanConfig.class);

    Author author = new Author();
    author.setAuthorID(112);
    author.setName("Ram");

    BaseDAO authordao = context.getBean(BaseDAO.class);
    authordao.insert(author);
    author = (Author) authordao.select(Author.class, 112);
    System.out.println("AuthorID:" + author.getAuthorID());
    System.out.println("Name:" + author.getName());
}

}

0 个答案:

没有答案