Srinivas
Srinivas

Reputation: 305

Kotlin Data class

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;
    }
}

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
            }
    }
}

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

Upvotes: 0

Views: 368

Answers (1)

Madhu Bhat
Madhu Bhat

Reputation: 15253

The RestProperties class can be converted into Kotlin as below:

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

    class Client {
        var defaultMaxTotalConnections: Int = 0
        var defaultMaxConnectionsPerRoute: Int = 0
        var defaultReadTimeout: Int = 0
    }
}

Do note that the properties need to be added as below in the application.yml to be injected correctly.

rest:
  client:
    defaultMaxTotalConnections: 1
    defaultMaxConnectionsPerRoute: 2
    defaultReadTimeout: 3

Also, a class like this which provides configuration should usually be annotated with @Configuration instead of @Component.

Upvotes: 5

Related Questions