Spring Data Jpa 自定义 Repository EntityManager is null

项目中升级了spring-data-jpa版本,发现继承了 QueryDslRepositorySupport 的自定义的Repository类一直报:

Caused by: java.lang.IllegalArgumentException: EntityManager must not be null!
    at org.springframework.util.Assert.notNull(Assert.java:134) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.jpa.repository.support.QueryDslRepositorySupport.validate(QueryDslRepositorySupport.java:75) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 23 common frames omitted

旧版本为: 1.11.4.RELEASE
新版本为: 1.11.8.RELEASE

对比源代码:
1.11.4:

    /**
     * Setter to inject {@link EntityManager}.
     * 
     * @param entityManager must not be {@literal null}
     */
    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {

        Assert.notNull(entityManager, "EntityManager must not be null!");
        this.querydsl = new Querydsl(entityManager, builder);
        this.entityManager = entityManager;
    }

1.11.8:

    /**
     * Setter to inject {@link EntityManager}.
     * 
     * @param entityManager must not be {@literal null}.
     */
    public void setEntityManager(EntityManager entityManager) {

        Assert.notNull(entityManager, "EntityManager must not be null!");
        this.querydsl = new Querydsl(entityManager, builder);
        this.entityManager = entityManager;
    }

新版本中去除了 @PersistenceContext 注解, 无法自动进行注入, 应该是新版本为了支持微服务, 表分库策略, 可以使用多个数据源, 多个EntityManager, 故移除自动注入, 改为手动注入:

@Autowired
    public CustomerRepositoryImpl(JpaContext context){
        super(Customer.class);
        setEntityManager(context.getEntityManagerByManagedType(Follow.class));
    }

你可能感兴趣的:(spring)