下面没有创建bean dataSource。由于这个原因,创建entityManagerFactory bean 时出现问题。我的问题是为什么没有创建 bean dataSource?未创建 bean 的原因是内存数据库中 H2 的连接问题吗?可能是什么原因?我需要在类路径中添加任何内容吗?
@TestConfiguration
@ActiveProfiles("localtest")
@TestPropertySource( locations = "classpath:application-localtest.properties")
public class H2Test {
@Autowired
private Environment env;
@Value("org.h2.Driver")
private String dbUrl;
@Value("jdbc:h2:mem:test")
private String dbDriverClass;
@Value("sa")
private String dbUser;
@Primary
@Bean(name="dataSource")
@Profile("localtest")
@ConditionalOnMissingBean
public DataSource dataSource() throws Exception{
System.out.println("___ DataSource construction started ___");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(dbDriverClass);
dataSource.setUrl(dbUrl);
dataSource.setUsername(dbUser);
dataSource.setPassword("");
ResourceDatabasePopulator rdp = new ResourceDatabasePopulator();
rdp.setScripts(new ClassPathResource("/test/data/Create_Tables.sql"));
rdp.execute(dataSource);
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[]{
"xx.xxx.xxxx"});
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
日志中显示的错误是-
创建在 x.xx.xx.xx.xxx.H2Test 中定义的名为“entityManagerFactory”的 bean 时出错:通过工厂方法实例化 Bean 失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]:工厂方法“entityManagerFactory”抛出异常;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为“dataSource”的 bean 可用
我在 application-localtest.properties 中定义了所有内容来创建连接。看起来像-
spring.profiles.active=localtest
spring.config.use-legacy-processing=true
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.defer-datasource-initialization=true
spring.sql.init.mode=always
spring.h2.console.path=/h2-console
h2.tcp.enabled=true
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.format_sql=true
spring.h2.console.enabled=true
spring.jpa.show-sql=true
问题可能出在哪里?我应该准确关注哪里?
您可以尝试进行“清理并构建”,然后再次运行该程序吗?通常这会有所帮助!