I'm trying to figure out the most efficient way to store a map of dictionary values at spring bean. This bean should return a message, stored in the mentioned map by code. For example the dictionary with about 11 elements, like:
[
{
1: "critical case"
},
{
2: "common processing error"
},
...
]
and a bean
@Component
class ErrorAnalyzer {
fun aggregateErrorDescriptions(errors: List<Int>): String {
// need to get all code descriptions from dictionary by errors
}
}
I assume, that it is a bad approach to store my dictionary as a static variable in companion object
of that bean like:
companion object {
private val dictionary = mapOf(
1 to "critical case",
2 to "common processing error"
)
}
Perhaps a lazy-loaded map sounds better but i'm not sure that it is much more efficient though...
val lazyValue: Map<Int, String> by lazy {
mapOf(
1 to "critical case",
2 to "common processing error"
)
}
Also the lazy map way can be modified by loading from a resource json file, but that's only for 11 elements... Also i have a feeling, that no elements would be added to this map in future...
What is preferrable / your way of this?
CodePudding user response:
Well, maybe I didn't understand the question right but if you need this map globally then just create it as a bean, something like this:
@Bean
fun nameOfADictionary(): Map<Int, String> = mapOf(...)
in a @Configuration
class and then inject it where you need in the context.
Otherwise, if you only need it somewhere locally, then create the map in a file / class where it'll be used as a private object and that's it. You don't even need the companion object
feature here.
Also if we talk about 11 elements in a collection, in my opinion, you don't need to mind about performance issues, just use the KISS principle.