spring-boot - IntelliJ 不获取自己的 spring 配置元数据
问题描述
我在 IntelliJ 使用 Gradle 获取自定义弹簧配置元数据时遇到问题。
如果我使用 Initializer 创建一个新的 Spring Boot 项目,在依赖项中包含配置处理器,在 Gradle 任务上设置以下任务,
创建一个包含以下内容的类:
package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("mycustomconfig")
public class MyCustomConfig {
private String name;
public String getName() {
return name;
}
public MyCustomConfig setName(String name) {
this.name = name;
return this;
}
}
然后 IntelliJ 在类文件“Spring Boot Configuration Annotation Processor not found in classpath”中抱怨,即使它肯定在类路径上。
运行应用程序后,会生成一个文件,build/classes/java/main/META-INF/spring-configuration-metadata.json
内容如下:
{
"groups": [
{
"name": "mycustomconfig",
"type": "com.example.demo.MyCustomConfig",
"sourceType": "com.example.demo.MyCustomConfig"
}
],
"properties": [
{
"name": "mycustomconfig.name",
"type": "java.lang.String",
"sourceType": "com.example.demo.MyCustomConfig"
}
],
"hints": []
}
但是 IntelliJ 然后在 application.properties 中抱怨:Cannot resolve configuration property "mycustomconfig.name".
同样的实验在 Maven 上也能完美运行。有什么我做错了吗?
我正在使用 IntelliJ 2018.3 Ultimate。
我的 build.gradle 是:
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
解决方案
最后,我找到了问题的原因。
注释处理器输出spring-configuration-metadata.json
到 build/classes/java/main/META-INF`。
但是:IntelliJ 使用不同的类路径进行解析。转到项目结构/模块/主模块/路径,您可以看到编译器输出设置为“使用模块编译输出路径”并指向out/production/classes
. 这是从 Gradle 自动解决的;一旦您在 Gradle 中进行任何更改,更改它将被还原。
我发现有两种可能:
在 IntelliJ Preferences/Build、Execution、Deployment/Compiler/Annotation Processors 中手动配置 Spring Boot 注解处理器,设置如下:
这样做的好处是,您不需要运行完整的 gradle 构建 - 只需从 IntelliJ 编译即可。不幸的是,项目中的每个用户似乎都是手动设置的。
在这个 Stack overflow question中提到了第二种可能性。idea
在 Gradle 中设置此选项:
idea{
module{
inheritOutputDirs = false
outputDir = compileJava.destinationDir
testOutputDir = compileTestJava.destinationDir
}
}
这基本上现在为 IntelliJ 和 Gradle 使用一个已编译的目标类。不过,如链接网址中所述,似乎有一些警告。