hello channel I am working on a Kotlin + Spring ap...
# spring
t
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
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
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
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
I would use simple factories
t
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
Copy code
@Component
class EntityBFactory(val config: SomeProperties) {
   fun create(): EntityB = ...
}
a
@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
yeah, I don’t like it either 😕