Kotlin Data class

Sri*_*vas 0 kotlin

I have below POJO in java which is used in Spring boot app to inject properties from YML during the app startup. Trying to convert the app into Kotlin but I have struggle implementing the values injected when I converted the POJO to data class.

@Component
@ConfigurationProperties("rest")
@Data
public class RestProperties {
    private final Client client = new Client();

    @Data
    public static class Client {
        private int defaultMaxTotalConnections;
        private int defaultMaxConnectionsPerRoute;
        private int defaultReadTimeout;
    }
}
Run Code Online (Sandbox Code Playgroud)

I have tried below solution but didn't work.

@Component
@ConfigurationProperties("rest")
class RestProperties {
    val client = Client()

    class Client() {
        constructor(
            defaultMaxTotalConnections: Int, 
            defaultMaxConnectionsPerRoute: Int, 
            defaultReadTimeout: Int
        ) : this()
    }
}

@Component
@ConfigurationProperties("rest")
class RestProperties {
    val client = Client()

    class Client {
        var defaultMaxTotalConnections: Int = 50
            set(defaultMaxTotalConnections) {
                field = this.defaultMaxTotalConnections
            }

        var defaultMaxConnectionsPerRoute: Int = 10
            set(defaultMaxConnectionsPerRoute) {
                field = this.defaultMaxConnectionsPerRoute
            }

        var defaultReadTimeout: Int = 15000
            set(defaultReadTimeout) {
                field = this.defaultReadTimeout
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

second code works but the values are not injected from YML. Appreciate your help.

Mad*_*hat 5

RestProperties类可以转化成科特林如下:

@Component
@ConfigurationProperties("rest")
class RestProperties {
    val client: Client = Client()

    class Client {
        var defaultMaxTotalConnections: Int = 0
        var defaultMaxConnectionsPerRoute: Int = 0
        var defaultReadTimeout: Int = 0
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,需要按如下所示添加属性以application.yml正确注入。

rest:
  client:
    defaultMaxTotalConnections: 1
    defaultMaxConnectionsPerRoute: 2
    defaultReadTimeout: 3
Run Code Online (Sandbox Code Playgroud)

同样,通常会使用@Configuration代替这样的提供配置的类进行注释@Component