Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - inject map<Enum,Class> from application.yml

I use spring boot in a J2SE app.

I have some constant data, such as a map, indicating a HandlerClass to process one operation Type.

The map relation is not changed, so I want to config it in application.yml

I try this:

info:
  modify_nodeip: omm.task.impl.ModifyNodeIpHandler

But the map is only can be recognized as Map<String,String>, How can I inject the map as Map<Enum,Class>?

Thank you!

Updated: I followed @cfrick instruction, but it doen'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 func used the configuration

@Autowired
private TestConfiguration testConfiguration;

what's wrong with that? But it doesn't work, optHandlerMap in testConfiguration is null.

like image 262
NingLee Avatar asked Oct 27 '14 03:10

NingLee


1 Answers

You can play a trick like this:

In your TestConfiguration, define a Map<String,String>, and getter.

then provide a Map<Operator,Handler> getXXXX() function, in this function, convert the Map<String,String> to Map<Operator,Handler>.

Maybe you need to use reflect to new a instance.

By the way, you can use Maps.transform() in Guava to perform the conversion.

like image 95
shangyin Avatar answered Oct 07 '22 16:10

shangyin