spring-configuration-metadata.json file is not gen

2019-04-05 19:36发布

问题:

I'm trying to generate spring-configuration-metadata.json file for my Spring Boot based project. If I use Java @ConfigurationProperties class it is generated correctly and automatically:

@ConfigurationProperties("myprops")
public class MyProps {

    private String hello;

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }
}

But if I use Kotlin class the spring-configuration-metadata.json file is not generated (I've tried both gradle build and Idea Rebuild Project).

@ConfigurationProperties("myprops")
class MyProps {
    var hello: String? = null
}

AFAIK Kotlin generates the same class with constructor, getters and setters and should act as regular Java bean.

Any ideas why spring-boot-configuration-processor doesn't work with Kotlin classes?

回答1:

Thank you for pointing me in the right direction. So the solution is to add

dependencies {
    ...
    kapt "org.springframework.boot:spring-boot-configuration-processor"
    optional "org.springframework.boot:spring-boot-configuration-processor"
    ...
}

to build.gradle file, run gradle compileJava in command line and turn on annotation processing in IntelliJ Idea settings Build, Execution, Deployment -> Compiler -> Annotation processor -> Enable anotation processing. The rest of configuration remains the same

Also note that without this line

optional "org.springframework.boot:spring-boot-configuration-processor"

IntelliJ Idea will complain whith

Cannot resolve configuration property

message in your application.properties or application.yml



回答2:

For those who want to use Maven instead of Gradle, you need to add an kapt execution to the kotlin-maven-plugin configuration.

<execution>
    <id>kapt</id>
    <goals>
        <goal>kapt</goal>
    </goals>
    <configuration>
        <sourceDirs>
            <sourceDir>src/main/kotlin</sourceDir>
        </sourceDirs>
        <annotationProcessorPaths>
            <annotationProcessorPath>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <version>1.5.3.RELEASE</version>
            </annotationProcessorPath>
        </annotationProcessorPaths>
    </configuration>
</execution>

There is an open issue KT-18022 that prevents this from working if an compiler plugin such as kotlin-maven-allopen is declared as dependency.



回答3:

Kotlin has its own compiler. The meta-data is generated by an annotation processor that is a hook-point in the Java compiler.

I have no idea if such hook-point is available in Kotlin but in any case, Spring Boot does not support anything else than Java at the moment. Maybe this would help?