4

In my code, I have an HPContentModule:

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

I am wondering if it is possible to get a String such that:

String myString = "hpContentModule";

so that I can then call hpContentModule using myString, doing something like myString.init();, where init() is a method in HPContentMethod?

Or,

If I have the bean:

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

Can I call this bean by String in the controller?

Xynariz
  • 1,232
  • 1
  • 11
  • 28
Ilkar
  • 2,113
  • 9
  • 45
  • 71
  • 4
    I suspect that depends on your DI/IOC framework. Which one are you using? – Peter Lawrey Sep 14 '12 at 19:59
  • 2
    http://stackoverflow.com/a/11741450/106261 – NimChimpsky Sep 14 '12 at 20:05
  • 1
    You should be able to just call whatever container is providing the resource annotation to look up the resource by name and then pass myString as the argument (if that's what you're asking for), though that would defeat the purpose of the injection. After the value is injected you should be able to use reflection. – Matt Whipple Sep 14 '12 at 20:23
  • I'm using Spring and i'm trying to dynamically load module. – Ilkar Sep 14 '12 at 20:39
  • What's stopping you from getting the bean context and accessing/casting the bean based on the String? Of interest, one thing that I found recently was that you can assign `` values dynamically. By that, I meant that you can load a resource file that supplies the name of the bean that you are interested in loading (e.g., ``). – pickypg Sep 14 '12 at 21:03
  • I want to create web template with dynamic loading modules. Names of modules are saved in database, so i'm getting data string and loading module. Thahs why i need to load bean by String. – Ilkar Sep 14 '12 at 21:08
  • If you want to load different modules dynamically, then you probably don't want to use injection. – jahroy Sep 14 '12 at 23:02

1 Answers1

0

There are a number of ways this can be done.

One of the simplest is with Spring's ApplicationContext. There are several ways you can gain access to the ApplicationContext. Once you have a copy of the ApplicationContext you can call the getBean() method like so:

HPContentModule hpContentModule = (HPContentModule) appContext.getBean( "myBean" );
brettjonesdev
  • 2,271
  • 1
  • 18
  • 23