Spring Load input map <Enum, Class> from .yml application
I am using spring boot in J2SE application.
I have some persistent data such as a map indicating HandlerClass
to handle a single operation.
The relation of the map does not change, so I want to customize it in application.yml
I am trying this:
info:
modify_nodeip: omm.task.impl.ModifyNodeIpHandler
But the display can only be recognized as Map<String,String>
. How can I insert the card how Map<Enum,Class>
?
Thank!
Updated: I followed @cfrick's instruction, but it doesn't work.
application.yml
config:
optHandlerMap:
modify_oms_nodeip: 'omm.task.opthandler.impl.ModifyOMSNodeIpHandler'
TestConfiguration:
@Configuration
@ConfigurationProperties(prefix = "config")
public class TestConfiguration
{
Map<OperationType,OptHandler> optHandlerMap; // here we store the handlers, same name in yaml
TestConfiguration() {}
}
and the main function used the configuration
@Autowired
private TestConfiguration testConfiguration;
what's wrong with it? But that doesn't work, optHandlerMap
in testConfiguration
is null.
source to share
You can play the trick like this:
The TestConfiguration
point and getter.
then provide a function Map<Operator,Handler> getXXXX()
, in that function, convert Map<String,String>
to Map<Operator,Handler>
.
Perhaps you need to use new instance mapping.
By the way, you can use Maps.transform()
Guava to do the conversion.
source to share
You write your own settings and comment like @ConfigurationProperties
(see 21.6 Configuration Configuration Properties )
@Component
@ConfigurationProperties(prefix="cfg") // the root in my yaml
class HandlerConfiguration {
public enum Handler { Handler1, Handler2 } // enum
Map<Handler,Class> handlers // here we store the handlers, same name in yaml
HandlerConfiguration() {}
}
Then mine application.yaml
looks like this:
cfg:
handlers:
Handler1: 'app.Handler1'
And access to it like this:
def ctx = SpringApplication.run(Application, args)
ctx.getBean(HandlerConfiguration).with{
assert handlers.size()==1 // there is the one
assert handlers[HandlerConfiguration.Handler.Handler1] // it key is the enum
assert handlers[HandlerConfiguration.Handler.Handler1] == Handler1 // its value is the actual class
handlers[HandlerConfiguration.Handler.Handler1].newInstance().run()
}
( app.Handler1
- this is just some random class that I put there, all in one package ( app
))
source to share