【问题标题】:Caused by: java.lang.IllegalStateException: required key [datasource.sampleapp.hibernate.dialect] not found原因:java.lang.IllegalStateException: required key [datasource.sampleapp.hibernate.dialect] not found
【发布时间】:2017-05-16 07:30:31
【问题描述】:

我正在关注链接中的相同代码:http://websystique.com/spring-boot/spring-boot-angularjs-spring-data-jpa-crud-app-example/。但是当我简单地运行Spring Boot的main方法时,我看到下面的错误来了。你能指导一下吗?我正在使用Java 7

 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/websystique/springboot/configuration/JpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.IllegalStateException: required key [datasource.sampleapp.hibernate.dialect] not found
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1134) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1028) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
        at com.websystique.springboot.SpringBootCRUDApp.main(SpringBootCRUDApp.java:15) ~[classes/:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.IllegalStateException: required key [datasource.sampleapp.hibernate.dialect] not found
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        ... 18 common frames omitted
    Caused by: java.lang.IllegalStateException: required key [datasource.sampleapp.hibernate.dialect] not found
        at org.springframework.core.env.AbstractPropertyResolver.getRequiredProperty(AbstractPropertyResolver.java:183) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.core.env.AbstractEnvironment.getRequiredProperty(AbstractEnvironment.java:556) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at com.websystique.springboot.configuration.JpaConfiguration.jpaProperties(JpaConfiguration.java:98) ~[classes/:na]
        at com.websystique.springboot.configuration.JpaConfiguration.entityManagerFactory(JpaConfiguration.java:80) ~[classes/:na]
        at com.websystique.springboot.configuration.JpaConfiguration$$EnhancerBySpringCGLIB$$3ce60e74.CGLIB$entityManagerFactory$2(<generated>) ~[classes/:na]
        at com.websystique.springboot.configuration.JpaConfiguration$$EnhancerBySpringCGLIB$$3ce60e74$$FastClassBySpringCGLIB$$a174a592.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        at com.websystique.springboot.configuration.JpaConfiguration$$EnhancerBySpringCGLIB$$3ce60e74.entityManagerFactory(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_25]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_25]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_25]
        at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_25]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
        ... 19 common frames omitted

application.yml

---
server:
  port: 8080
  contextPath: /SpringBootCRUDApp
---
spring:
  profiles: local
datasource:
  sampleapp:
    url: jdbc:h2:~/test
    username: SA
    password:
    driverClassName: org.h2.Driver
    defaultSchema:
    maxPoolSize: 10
    hibernate:
      hbm2ddl.method: create-drop
      show_sql: true
      format_sql: true
      dialect: org.hibernate.dialect.H2Dialect
---
spring:
  profiles: prod
datasource:
  sampleapp:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
    driverClassName: com.mysql.jdbc.Driver
    defaultSchema:
    maxPoolSize: 20
    hibernate:
      hbm2ddl.method: update
      show_sql: true
      format_sql: true
      dialect: org.hibernate.dialect.MySQLDialect

pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
        <h2.version>1.4.187</h2.version>
    </properties>

    <dependencies>
        <!-- Add typical dependencies for a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Add freemarker template support -->        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- Add JPA support -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Add Hikari Connection Pooling support -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>

        <!-- Add H2 database support [for running with local profile] -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>${h2.version}</version>
        </dependency>

        <!-- Add MySQL database support [for running with PRODUCTION profile] -->       
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
    </dependencies>



    <build>
        <plugins>
            <plugin><!-- Include if you want to make an executable jar[FAT JAR which 
                    includes all dependencies along with sprinboot loader] that you can run on 
                    commandline using java -jar NAME -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

SpringBootCRUDApp.java

@Import(JpaConfiguration.class)
@SpringBootApplication(scanBasePackages={"com.websystique.springboot"})// same as @Configuration @EnableAutoConfiguration @ComponentScan
public class SpringBootCRUDApp {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootCRUDApp.class, args);
    }
}

JpaConfiguration.java

@Configuration
@EnableJpaRepositories(basePackages = "com.websystique.springboot.repositories",
entityManagerFactoryRef = "entityManagerFactory",transactionManagerRef = "transactionManager")
@EnableTransactionManagement
public class JpaConfiguration {

    @Autowired
    private Environment environment;

    @Value("${datasource.sampleapp.maxPoolSize:10}")
    private int maxPoolSize;

    /*
     * Populate SpringBoot DataSourceProperties object directly from application.yml 
     * based on prefix.Thanks to .yml, Hierachical data is mapped out of the box with matching-name
     * properties of DataSourceProperties object].
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "datasource.sampleapp")
    public DataSourceProperties dataSourceProperties(){
        return new DataSourceProperties();
    }

    /*
     * Configure HikariCP pooled DataSource.
     */
    @Bean
    public DataSource dataSource() {
        DataSourceProperties dataSourceProperties = dataSourceProperties();
        HikariDataSource dataSource = (HikariDataSource) DataSourceBuilder
                .create(dataSourceProperties.getClassLoader())
                .driverClassName(dataSourceProperties.getDriverClassName())
                .url(dataSourceProperties.getUrl())
                .username(dataSourceProperties.getUsername())
                .password(dataSourceProperties.getPassword())
                .type(HikariDataSource.class)
                .build();
        dataSource.setMaximumPoolSize(maxPoolSize);
        return dataSource;
    }

    /*
     * Entity Manager Factory setup.
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setPackagesToScan(new String[] { "com.websystique.springboot.model" });
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        factoryBean.setJpaProperties(jpaProperties());
        return factoryBean;
    }

    /*
     * Provider specific adapter.
     */
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        return hibernateJpaVendorAdapter;
    }

    /*
     * Here you can specify any provider specific properties.
     */
    private Properties jpaProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("datasource.sampleapp.hibernate.dialect"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("datasource.sampleapp.hibernate.hbm2ddl.method"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("datasource.sampleapp.hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("datasource.sampleapp.hibernate.format_sql"));

        if(StringUtils.isNotEmpty(environment.getRequiredProperty("datasource.sampleapp.defaultSchema"))){
            properties.put("hibernate.default_schema", environment.getRequiredProperty("datasource.sampleapp.defaultSchema"));
        }
        return properties;
    }


    @Bean
    @Autowired
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(emf);
        return txManager;
    }
}

【问题讨论】:

  • 我建议遵循一个好的教程。喜欢this one。您遵循的指南基本上忽略了正在使用 Spring Boot 的事实。
  • 尝试像 public static void main(String[] args) { SpringApplicationBuilder(SpringBootCRUDApp.class) .properties("datasource.sampleapp.hibernate.dialect=org.hibernate.dialect.MySQLDialect").run(args); 这样传递该属性,如果它现在抱怨下一个属性,application.yml 加载
  • 方法 SpringApplicationBuilder(Class) 未定义 SpringBootCRUDApp 类型 - 您的建议不起作用
  • @Deinum ,据我所知,是什么让您说该指南忽略了使用弹簧靴的事实?

标签: angularjs spring-boot spring-batch


【解决方案1】:

您可以为 2 个不同的环境(例如 dev/prod)创建活动配置文件来解决此问题。如果您使用 Eclipse 创建一个应用程序来启动并在尝试启动应用程序时添加 VM 参数,

for dev
  -Dspring.profiles.active=local 
for production
  -Dspring.profiles.active=prod  

如果你想以 jar 的形式运行,

 for Dev,
     java -jar SpringBootCRUDApplicationExample-1.0.0.jar --spring.profiles.active=local

for Production,
 java -jar SpringBootCRUDApplicationExample-1.0.0.jar --spring.profiles.active=prod

【讨论】:

    【解决方案2】:

    我没有足够的代表发表评论,但你记得使用个人资料运行吗?该错误通常表明您不是。

    教程还说您使用配置文件运行。

    在运行我们的示例时 [通过 IDE 或命令行],我们可以提供 配置文件信息使用 -Dspring.profiles.active=local 或 -Dspring.profiles.active=prod 在 VM 参数中[用于 IDE] 或命令行 java -jar JARPATH --spring.profiles.active=local。

    原因是 Spring 需要从您的属性文件(在本例中为 yml 文件)中知道要使用哪些属性。

    【讨论】:

      【解决方案3】:

      为默认和本地创建单独的配置文件。它对我有用。

      spring:
        profiles: default
      datasource:
        sampleapp:
          url: jdbc:h2:~/test
          username: SA
          password:
          driverClassName: org.h2.Driver
          defaultSchema:
          maxPoolSize: 10
          hibernate:
            hbm2ddl.method: create-drop
            show_sql: true
            format_sql: true
            dialect: org.hibernate.dialect.H2Dialect
      

      spring:
        profiles: local
      datasource:
        sampleapp:
          url: jdbc:h2:~/test
          username: SA
          password:
      

      【讨论】:

      【解决方案4】:

      如果您使用的是 Eclipse... 只需右键单击 pom.xml -> Run As -> Run Configurations。然后它将打开新的弹出窗口,您可以在 Java 应用程序下看到 SpringBootCRUDApp...在右侧弹出窗口..选择参数选项卡...您可以将第二个文本作为 VM 参数..只需粘贴“-Dspring. profile.active=local".. 然后运行它.. 它会工作...

      如果您从 cmd 提示符运行 对于开发, java -jar SpringBootCRUDApplicationExample-1.0.0.jar --spring.profiles.active=local

      对于生产, java -jar SpringBootCRUDApplicationExample-1.0.0.jar --spring.profiles.active=prod

      --Njoy

      【讨论】:

        【解决方案5】:

        在 Eclipse 中,要运行 spring boot 应用程序,请在运行配置中的 VM 参数中添加配置文件, 对于开发人员,您可以添加 -Dspring.profiles.active=本地 对于生产,您可以添加 -Dspring.profiles.active=产品 请在截图中找到 eclipse_spring_profile_vm_args.JPG

        【讨论】:

          猜你喜欢
          • 2022-06-27
          • 2016-01-22
          • 2019-07-03
          • 1970-01-01
          • 1970-01-01
          • 2017-04-09
          • 1970-01-01
          • 2015-05-30
          • 2020-10-24
          相关资源
          最近更新 更多