https://kotlinlang.org logo
#spring
Title
# spring
t

Tiago

01/16/2023, 5:23 PM
hello channel I am working on a Kotlin + Spring application, and wondering if this is possible or not: there is a properties configuration:
Copy code
@ConfigurationProperties("application.custom.properties")
data class SomeProperties(
    val foo: Long,
    val bar: String,
)
application.properties:
Copy code
application.custom.properties.foo=1
application.custom.properties.bar=Text Here
ok, so I have another class, just a POJO, and need to get the values from that configuration properties bean
Copy code
data class ObjectBuilder(
    var fooValue: Long = SomeProperties.foo,
    var barValue: String = SomeProperties.bar,
)
is there a way of getting the SomeProperties values on a non spring context?
a

ashmelev

01/16/2023, 5:27 PM
Something like this should work:
Copy code
@Bean(name = ["objectBean"])
  fun objectBean(): ObjectBuilder =
      ObjectBuilder(
		fooValue = SomeProperties.foo,
		barValue = SomeProperties.bar
        )
Then just inject
objectBean
wherever you need it
t

Tiago

01/16/2023, 7:43 PM
lets try another scenario:
Copy code
@Entity
data class EntityA(
  var entityB: EntityB
)

@Entity
data class EntityB(
  var foo: Long = SomeProperties.foo
)
I want to use the
SomeProperties.foo
as the default value for EntityA.entityB.foo
a

ashmelev

01/16/2023, 9:23 PM
Well, @Entity does not create a Bean (AFAIK), so you'd have to add @Component to the @Entity and then inject
objectBean
. Try something like:
Copy code
@Entity
@Component
data class EntityB(
  @Transient private val objectBean: ObjectBuilder,
  var foo: Long = objectBean.fooValue
)
Obviously I have not tested this so I am not sure it will actually inject properly
k

kqr

01/17/2023, 8:50 AM
I would use simple factories
t

Tiago

01/17/2023, 9:14 AM
like how? 🤔
I am using @PostConstruct to store the instance from the bean on a static context:
Copy code
@PostConstruct
fun initialize() {
    instance = this
}
And then I can access this instance from a non-spring context but I am not completely happy with this approach 😆
k

kqr

01/17/2023, 9:50 AM
Copy code
@Component
class EntityBFactory(val config: SomeProperties) {
   fun create(): EntityB = ...
}
a

ashmelev

01/17/2023, 3:45 PM
@Tiago’s approach will work well too. I just have a personal preference against doing the necessary initialization in @PostConstruct. Not that it is wrong or would fail - it will work. Just seems untidy to my eyes 🙂
t

Tiago

01/17/2023, 4:45 PM
yeah, I don’t like it either 😕
51 Views