hey Channel. I am accustomed to inject beans usin...
# spring
a
hey Channel. I am accustomed to inject beans using Springboot doing, for example:
Copy code
@Autowired
private AccountMapper mapper;
I want to avoid of instantiate a HttpClient builder every time in my
@Component
class. Instead of do
val client = HttpClient.newBuilder().build()
every time, please let me know how to inject it using Kotlin.
s
Copy code
@Configuration
class HttpClientConfiguration {
    @Bean
    fun httpClient(): HttpClient = HttpClient.newBuilder().build()
}
1
👍 1
d
Just be careful, because this would create a singleton bean which is shared by all of your code and this may mess with things if the client does not work well when it's shared
👍 1
a
thank you Guys!
hey @Sam Considering this example, how to use it? Maybe in my Component Class by constructor?
s
Yep, once you have declared the configuration class, you will be able to autowire the HTTP client inside other component classes, including via constructor injection 👍
d
You don't need the Autowired annotation, just put it into the constructor and Spring will inject it
👍 1
a
Awesome. Yeah! It’s hard forget Java/Spring and think in Kotlin, I am learning Kotlin and trying to apply these concepts related to Functional Program.
d
Well it works the same in Java, this is more due to Spring than Kotlin
s
There is a way to declare beans in functional style in Kotlin but I haven’t seen it used much. Can’t find the docs 🤔
a
Thank you for this awesome information guys. I did two Kotlin courses but I am still struggling with specific points… like how to convert ByteArray to Byte[] and how to do the same as we can do using Java StreamAPI but in Kotlin I am struggling yet
Thank you for this tip about the injection
s
Off-topic, but for
ByteArray
->
Byte[]
use
toTypedArray()
😉
a
hey @Sam
please, could you clarify that?
I tried to use this
toTypedArray()
but I didn’t manage to
s
A
ByteArray
in Kotlin is equivalent to a java primitive
byte[]
array. You can call
.toTypedArray()
on it to convert it to a Kotlin
Array<Byte>
, which is equivalent to a boxed Java
Byte[]
array.
a
I will try again here. Thank you