按字符串调用引用

4

在我的代码中,我有一个HPContentModule:

@Resource(name = "HPContentModule")
private HPContentModule hpContentModule;

我想知道是否有可能获得一个字符串,使其满足以下条件:String
String myString = "hpContentModule";

那么我可以使用myString调用hpContentModule,像这样执行myString.init();,其中init()HPContentMethod中的一个方法吗?

或者,

如果我有这个bean:

<beans:bean id="myBean" class="com.app.search.HPContent" />

在控制器中,我可以通过String调用这个bean吗?


4
我猜这取决于你的 DI/IOC 框架。你使用的是哪一个? - Peter Lawrey
2
https://dev59.com/_2gt5IYBdhLWcg3w5hWr#11741450 - NimChimpsky
1
你应该能够调用提供资源注释的任何容器,通过名称查找资源,然后将myString作为参数传递(如果这是你要求的),尽管这会破坏注入的目的。注入值后,你应该能够使用反射。 - Matt Whipple
我正在使用Spring,尝试动态加载模块。 - Ilkar
有什么阻止你获取bean上下文并根据字符串访问/转换bean的方法吗?有趣的是,我最近发现的一件事是,您可以动态地分配<constructor-arg ref="..." />值。我的意思是,您可以加载一个资源文件,该文件提供您要加载的bean的名称(例如,<constructor-arg ref="${hpContentModuleName}" />)。 - pickypg
显示剩余2条评论
1个回答

0

有许多方法可以实现这一点。

其中最简单的方法之一是使用Spring的ApplicationContext。 有几种方式可以访问ApplicationContext。 一旦您拥有ApplicationContext的副本,就可以像这样调用getBean()方法:

HPContentModule hpContentModule = (HPContentModule) appContext.getBean( "myBean" );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接