Spring Boot - 从 application.yml 注入 map<Enum,Class>

Nin*_*Lee 6 yaml initialization spring-boot

我在 J2SE 应用程序中使用 Spring Boot。

我有一些常量数据,比如地图,表示一个HandlerClass处理一个操作的类型。

映射关系没有改变,所以我想在 application.yml 中配置它

我试试这个:

info:
  modify_nodeip: omm.task.impl.ModifyNodeIpHandler
Run Code Online (Sandbox Code Playgroud)

但是地图只能被识别为Map<String,String>,如何将地图注入为Map<Enum,Class>

谢谢!

更新: 我遵循@cfrick 指令,但它不起作用。

应用程序.yml

config:
    optHandlerMap:
        modify_oms_nodeip: 'omm.task.opthandler.impl.ModifyOMSNodeIpHandler'
Run Code Online (Sandbox Code Playgroud)

测试配置:

@Configuration
@ConfigurationProperties(prefix = "config")
public class TestConfiguration
{

    Map<OperationType,OptHandler> optHandlerMap; // here we store the handlers, same name in yaml
    TestConfiguration() {}

}
Run Code Online (Sandbox Code Playgroud)

并且主要功能使用了配置

@Autowired
private TestConfiguration testConfiguration;
Run Code Online (Sandbox Code Playgroud)

那有什么问题?但它不起作用,optHandlerMapintestConfiguration为空。

cfr*_*ick 0

您编写自己的设置并注释为@ConfigurationProperties(请参阅21.6 类型安全配置属性

@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() {}
}
Run Code Online (Sandbox Code Playgroud)

然后我的application.yaml样子是这样的:

cfg:
  handlers:
    Handler1: 'app.Handler1'
Run Code Online (Sandbox Code Playgroud)

并像这样访问它:

def ctx = SpringApplication.run(Application, args)
ctx.getBean(HandlerConfiguration).with{
    assert handlers.size()==1 // there is the one
    assert handlers[HandlerConfiguration.Handler.Handler1] // it's key is the enum
    assert handlers[HandlerConfiguration.Handler.Handler1] == Handler1 // its value is the actual class
    handlers[HandlerConfiguration.Handler.Handler1].newInstance().run()
}
Run Code Online (Sandbox Code Playgroud)

app.Handler1只是我放在那里的一些随机类,所有这些都在同一个包中(app))