下面没有创建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。Bean示例化异常:示例化[org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]失败:工厂方法“entityManagerFactory”引发异常;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为“dataSource”的Bean可用
我在www.example.com中定义了所有内容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
问题出在哪里?我应该把注意力集中在哪里?
1条答案
按热度按时间t5zmwmid1#
从dataSource()方法中删除@ConditionalOnMissingBean注解。