spring@autowired entitymanager失败

dxpyg8gm  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(326)

我正在研究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. 为什么?

eh57zj3b

eh57zj3b1#

经过几个小时的调试,我找到了一堆内部spring代码的原因。
这是:

@Autowired
private EntityManager entityManager;

只有当你有 @EnableJpaRepositories 注解。
例如:

@EnableJpaRepositories
@Configuration
public class ConfigurationA {}

也就是说,自动布线 EntityManager 是SpringDataJPA模块提供的一个特性。它不是由通常的springjpa集成提供的。

相关问题