创建Bean时出错 - 依赖项自动装配失败

时间:2016-08-19 11:24:39

标签: java maven spring-mvc

运行spring-mvc应用程序时出现此错误:

Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError

Error creating bean with name 'personDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.PersonDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError

我还检查了 pom.xml

中的依赖项
<!-- Spring -->
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>

<!-- Hibernate / JPA -->
<hibernate.version>5.2.1.Final</hibernate.version>

除此之外,我在所有依赖项的版本中指定了${spring-framework.version}${hibernate.version}

//////////////////////////////弹簧配置////////////// < / p>

package com.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.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.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.model.Person;
import com.service.PersonService;


@Configuration
@EnableWebMvc
@ComponentScan({ "com.*" })

@EnableTransactionManagement
public class SpringConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Environment environment;
    @Autowired
    private PersonService ps;

    @Bean @Autowired
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setAnnotatedClasses(Person.class);
        sessionFactory.setPackagesToScan(new String[] { "com.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean @Autowired
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
        dataSource.setUsername("root");
        dataSource.setPassword("admin123");
        return dataSource;
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // TODO Auto-generated method stub
        registry.addResourceHandler("/resources/**").addResourceLocations(
                "/resources/*");
    }
    @Bean @Autowired
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver res = new InternalResourceViewResolver();
        res.setPrefix("/WEB-INF/view/");
        res.setSuffix(".jsp");
        return res;
    }


    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect",
                "org.hibernate.dialect.MySQL5Dialect");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "update");
        properties.put("hibernate.search.default.directory_provider", "org.hibernate.search.store.impl.FSDirectoryProvider");
        properties.put("hibernate.search.default.indexBase", "H:/MyWorkspace/MainAssignment3/indexes");
        return properties;
    }
    @Bean @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }

     @Bean
        public MessageSource messageSource() {
            ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
            messageSource.setBasename("messages");
            return messageSource;
        }



}

/////////////////////////////////// POM /////////// /////////////////////

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.samples.service.service</groupId>
    <artifactId>MainAssignment3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>

        <!-- Generic properties -->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- Web -->
        <jsp.version>2.2</jsp.version>
        <jstl.version>1.2</jstl.version>
        <servlet.version>2.5</servlet.version>


        <!-- Spring -->
        <spring-framework.version>4.2.1.RELEASE</spring-framework.version>

        <!-- Hibernate / JPA -->
        <hibernate.version>5.1.1.Final</hibernate.version>

        <!-- Logging -->
        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>

    </properties>

    <dependencies>

        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>



        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> 
            <version>${spring-framework.version}</version> </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.3</version>
        </dependency>
        <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> 
            <version>1.1</version> </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>


        <!-- Other Web dependencies -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring-framework.version}</version>
</dependency>


        <!-- Spring and Transactions -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
         <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search-orm</artifactId>
        <version>5.5.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search-engine</artifactId>
        <version>5.5.4.Final</version>
    </dependency>
        <!-- Test Artifacts -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-framework.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

    </dependencies>
</project>

/////////////////////////////// DAO File ////////////// ////////////////

package com.dao;

import java.util.List;




import com.model.Person;

public interface PersonDAO {
    public void save(Person p);

    public List<Person> list();

    public void updatePerson(Integer id);

    public Person getPersonById(int id);

    public void removePerson(Integer id);

    public void indexPersons() throws Exception;

    public List<Person> searchForPerson(String searchText) throws Exception;

}

////////////////////////// DAO Impl /////////////////// ////////

package com.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.model.Person;

@Transactional
@Repository
public class PersonDAOImpl implements PersonDAO, java.io.Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private static final Logger logger = (Logger) LoggerFactory
            .getLogger(PersonDAOImpl.class);

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf) {
        this.sessionFactory = sf;
    }

    public void save(Person p) {
        // TODO Auto-generated method stub
        Session s = sessionFactory.openSession();
        Transaction tx = s.beginTransaction();
        s.saveOrUpdate(p);
        tx.commit();
        s.close();

        System.out.println("Record successfully inserted");

    }

    @SuppressWarnings("deprecation")
    public List<Person> list() {
        // TODO Auto-generated method stub
        Session session = this.sessionFactory.getCurrentSession();
        @SuppressWarnings("unchecked")
        List<Person> personsList = session.createQuery("from Person").list();
        for (Person p : personsList) {
            logger.info("Person List::" + p);
        }
        return personsList;

    }

    public void updatePerson(Integer id) {
        Session session = new Configuration().configure().buildSessionFactory()
                .openSession();
        Person p = new Person();
        Person person = session.get(Person.class, p.getId());


        //Transaction t = session.beginTransaction();
        Query query = session.createQuery("from Person");
        person.setName(p.getName()); // modify the loaded object somehow
        session.update(person);
        //t.commit();
        session.close();

    }

    public Person getPersonById(int id) {
        // TODO Auto-generated method stub
        Session session = this.sessionFactory.getCurrentSession();
        Person p = (Person) session.load(Person.class, new Integer(id));
        logger.info("Person loaded successfully, Person details=" + p);
        return p;
    }

    public void removePerson(Integer id) {
        Session session = sessionFactory.getCurrentSession();

//      Transaction t = session.beginTransaction();
        Person p = (Person) session.load(Person.class, new Integer(id));
        session.delete(p);
//      t.commit();
        logger.info("Person deleted successfully, person details=");

    }
    @Transactional
    public void indexPersons() throws Exception{
        // TODO Auto-generated method stub
          try
          {
             Session session = sessionFactory.getCurrentSession();

             FullTextSession fullTextSession = Search.getFullTextSession(session);
             fullTextSession.createIndexer().startAndWait();
          }
          catch(Exception e)
          {
             throw e;
          }
       }

    public List<Person> searchForPerson(String searchText) throws Exception{
        // TODO Auto-generated method stub
        try
          {
             Session session = sessionFactory.getCurrentSession();

             FullTextSession fullTextSession = Search.getFullTextSession(session);

             QueryBuilder qb = fullTextSession.getSearchFactory()
               .buildQueryBuilder().forEntity(Person.class).get();
             org.apache.lucene.search.Query query = qb
               .keyword().onFields("name", "address", "salary","gender")
               .matching(searchText)
               .createQuery();

             org.hibernate.Query hibQuery = 
                fullTextSession.createFullTextQuery(query, Person.class);

             List<Person> results = hibQuery.list();
             return results;
          }
          catch(Exception e)
          {
             throw e;
          }
       }


    }

1 个答案:

答案 0 :(得分:1)

根据docs,如果你想使用Hibernate 5.2,你应该将你的Spring依赖关系更新为4.3。

此外,你必须纠正Hibernate搜索的依赖关系(它的版本与Hibernate的核心不同)。

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search-orm</artifactId>
        <version>5.5.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search-engine</artifactId>
        <version>5.5.4.Final</version>
    </dependency>