@Component
class ClassWithDependencyFactory(
dependency: DependencyRepository,
) {
private val stuffListCache: List<String> = dependency.getAllStuff()
?.map { c -> c.code }
?: error("Failed to Stuff list")
fun factoryMethodStuff() = stuffListCache
@PostConstruct
private fun storeSingleton() {
instance = this
}
companion object {
fun instance() = instance
}
}
private lateinit var instance: ClassWithDependencyFactory
## Another example with Companion Object setter:
@Bean
fun factory(dependency: DependencyRepository) = ClassWithDependencyFactory(dependency).also{ClassWithDependencyFactory.setInstance(it)}
class ClassWithDependencyFactory(
dependency: DependencyRepository,
) {
private val stuffListCache: List<String> = dependency.getAllStuff()
?.map { c -> c.code }
?: error("Failed to Stuff list")
fun factoryMethodStuff() = stuffListCache
companion object {
private lateinit var instance: ClassWithDependencyFactory
fun setInstance(i : ClassWithDependencyFactory) {
this.instance = i
}
fun instance() = instance
}
}