【问题标题】:Issue with Spring Data JPA - BeanEntityManagerFactorySpring Data JPA 的问题 - Bean EntityManagerFactory
【发布时间】:2015-09-27 12:35:12
【问题描述】:

我最近开始学习春天。我正在尝试在 spring mvc 项目中使用 spring data jpa 的简单示例。在 tomcat 中部署 war 文件时出现以下错误。

Caused by: org.springframework.beans.factory.BeanCreationException: Error creati
ng bean with name '(inner bean)#584d15f2': Cannot resolve reference to bean 'ent
ityManagerFactory' while setting constructor argument; nested exception is org.s
pringframework.beans.factory.BeanCurrentlyInCreationException: Error creating be
an with name 'entityManagerFactory': Requested bean is currently in creation: Is
 there an unresolvable circular reference?
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver
.resolveReference(BeanDefinitionValueResolver.java:359)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver
.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
        at org.springframework.beans.factory.support.ConstructorResolver.resolve
ConstructorArguments(ConstructorResolver.java:634)
        at org.springframework.beans.factory.support.ConstructorResolver.instant
iateUsingFactoryMethod(ConstructorResolver.java:444)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:11
19)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.createBean(AbstractAutowireCapableBeanFactory.java:476)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver
.resolveInnerBean(BeanDefinitionValueResolver.java:299)
        ... 92 more
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: E
rror creating bean with name 'entityManagerFactory': Requested bean is currently
 in creation: Is there an unresolvable circular reference?
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
y.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:347)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
y.getSingleton(DefaultSingletonBeanRegistry.java:223)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBe
an(AbstractBeanFactory.java:299)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:194)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver
.resolveReference(BeanDefinitionValueResolver.java:351)
        ... 100 more
27-Sep-2015 17:56:45.304 INFO [http-apr-8080-exec-35] org.apache.catalina.startu
p.HostConfig.deployWAR Deployment of web application archive D:\ApacheTomcat\apa
che-tomcat-8.0.26\webapps\springTest.war has finished in 6,124 ms

我的控制器代码如下,

package com.demo.repo;

import com.demo.model.Customer;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;

import javax.activation.DataSource;
import javax.persistence.EntityManagerFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

/**
 * Handles requests for the application home page.
 */
@Controller
@Configuration
@EnableJpaRepositories("com.demo.repo")


@EnableTransactionManagement
public class HomeController {

    @Autowired
    customerRepository repository;

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

    /**
     * Simply selects the home view to render by returning its name.
     */

    @Bean(destroyMethod = "close")
    DataSource dataSource(Environment env) {
    HikariConfig dataSourceConfig = new HikariConfig();
    dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
    dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
    dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
    dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));

    return (DataSource) new HikariDataSource(dataSourceConfig);
    }


    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, 
                                                            Environment env) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource((javax.sql.DataSource) dataSource);
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    entityManagerFactoryBean.setPackagesToScan("com.demo.repo");

    Properties jpaProperties = new Properties();

    //Configures the used database dialect. This allows Hibernate to create SQL
    //that is optimized for the used database.
    jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));

    //Specifies the action that is invoked to the database when the Hibernate
    //SessionFactory is created or closed.
    jpaProperties.put("hibernate.hbm2ddl.auto", 
            env.getRequiredProperty("hibernate.hbm2ddl.auto")
    );

    //Configures the naming strategy that is used when Hibernate creates
    //new database objects and schema elements
    jpaProperties.put("hibernate.ejb.naming_strategy", 
            env.getRequiredProperty("hibernate.ejb.naming_strategy")
    );

    //If the value of this property is true, Hibernate writes all SQL
    //statements to the console.
    jpaProperties.put("hibernate.show_sql", 
            env.getRequiredProperty("hibernate.show_sql")
    );

    //If the value of this property is true, Hibernate will format the SQL
    //that is written to the console.
    jpaProperties.put("hibernate.format_sql", 
            env.getRequiredProperty("hibernate.format_sql")
    );

    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
    }


    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate );

         repository.save(new Customer("Jack", "Bauer"));
         repository.save(new Customer("Chloe", "O'Brian"));
         repository.save(new Customer("Kim", "Bauer"));
         repository.save(new Customer("David", "Palmer"));
         repository.save(new Customer("Michelle", "Dessler"));

         for(Customer customer : repository.findAll())
         {
             System.out.println("Log Results ::  "+customer.toString());
         }

        return "myhome";
    }

}

谁能建议我的代码有什么问题以及解决问题的任何建议。

【问题讨论】:

  • 您正在创建 1 个 bean 来统治它们。你的控制器也是你的配置,不要那样做。将您的控制器和配置拆分为 2 个单独的类。它们是不同的东西,你不应该把它们结合起来。

标签: spring spring-mvc jpa spring-data spring-data-jpa


【解决方案1】:

您的entityManagerFactory 似乎需要在同一配置文件中定义的dataSource

尝试将dataSource 的定义移动到另一个配置类,或者,不要将dataSource 作为参数传递,而是在entityManagerFactory 中需要时调用dataSource() 方法。

@Autowired
Environment env;

@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = 
                     new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource((javax.sql.DataSource) dataSource());
    ....
}

提示:不要混用 @Controller@Configuration。为每个文件创建一个不同的文件。

【讨论】:

  • 仅当配置在同一个类中时调用该方法才有效,否则您可以轻松地将其作为方法参数注入。这样,您可以根据需要将 JDBC 和 JPA 配置分开。哪个更好是个人喜好恕我直言:)。
猜你喜欢
  • 2020-06-20
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多