我正在研究springjpa集成,在尝试自动连线时出现了一些奇怪的行为 EntityManager
与 @Autowired
注解。
我有一个没有spring引导上下文支持的spring测试:
@ExtendWith(SpringExtension.class)
class JpaTransactionScopedPersistentContextTests {
@Configuration
@ComponentScan(basePackages = {
"packages"
})
static class TestConfiguration {}
@Autowired
private EntityAService entityAService;
@Test
void testEntityManagerWithoutTransaction () {
EntityA entityA = new EntityA();
entityAService.save(entityA);
}
}
服务定义如下:
@Service
public class EntityAService {
// @PersistenceContext - this works
@Autowired // this fails
private EntityManager entityManager;
public EntityA save (EntityA entityA) {
return entityManager.merge(entityA);
}
@Transactional
public EntityA saveInTransaction (EntityA entityA) {
return entityManager.merge(entityA);
}
}
我有以下jpa配置:
@EnableTransactionManagement
@Configuration
public class ConfigurationA {
@Bean
public DataSource dataSourceWithEmbeddedDatabaseBuilder () throws SQLException {
return new EmbeddedDatabaseBuilder()
.setName("test")
.setType(EmbeddedDatabaseType.H2)
.addScripts("classpath:/schema.sql")
.addScripts("classpath:/data.sql")
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory (DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan("packages");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
return entityManagerFactoryBean;
}
@Bean
public PlatformTransactionManager jpaTransactionManager (EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
spring抛出错误: No qualifying bean of type 'javax.persistence.EntityManager' available: expected at least 1 bean which qualifies as autowire candidate.
为什么?
1条答案
按热度按时间eh57zj3b1#
经过几个小时的调试,我找到了一堆内部spring代码的原因。
这是:
只有当你有
@EnableJpaRepositories
注解。例如:
也就是说,自动布线
EntityManager
是SpringDataJPA模块提供的一个特性。它不是由通常的springjpa集成提供的。