0

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.

1

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.