Gradle+QueryDSL+JPA2.1下APT生成QEntity时类加载失败问题
解决QueryDSL APT注解处理器找不到javax.persistence.Entity的问题
这个问题我之前也碰到过,核心原因是注解处理器的类路径和常规编译类路径是完全隔离的——哪怕Spring Boot Starter已经把JPA API jar加到了你的compileClasspath,负责生成QEntities的QueryDSL JPA注解处理器根本看不到这个依赖,所以才会抛出NoClassDefFoundError。
直接解决方案:把JPA API加到注解处理器类路径
你需要把包含javax.persistence.Entity的依赖也声明为annotationProcessor依赖,而不只是compile依赖。修改你的Gradle依赖配置:
dependencies { compile 'org.springframework.boot:spring-boot-starter-data-jpa' // 原有的QueryDSL APT JPA处理器依赖 annotationProcessor "com.querydsl:querydsl-apt:$querydslVersion:jpa" // 新增:将JPA API加入注解处理器类路径 annotationProcessor 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final' }
如果你的项目用了Spring Boot的依赖管理(一般都会用),还可以省略版本号,让Spring Boot帮你统一管理:
annotationProcessor 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api'
为什么这样能解决?
Gradle中,注解处理器运行在独立的类加载环境里,它的类路径由annotationProcessor配置项单独维护,和compile/implementation配置的类路径不共享。QueryDSL的JPA注解处理器在解析@Entity注解时,需要直接加载javax.persistence.Entity类,所以必须把这个依赖明确加到注解处理器的类路径中。
额外优化(可选)
Gradle 4.7已经支持原生的APT处理,你可以确保compileJava任务明确使用annotationProcessor配置的路径,避免潜在的路径问题:
compileJava { options.annotationProcessorGeneratedSourcesDirectory = file("$projectDir/src/generated2/java") // 显式指定注解处理器的类路径 options.annotationProcessorPath = configurations.annotationProcessor }
做完这些配置后,重新执行compileJava任务,应该就能正常生成QEntities了。
内容的提问来源于stack exchange,提问作者Archange




