1

I have 3 implementations of an interface, and in order to instantiate one of them I need to check a parameter from the database. I was planning to do it with the factory pattern, but since I'm using JSF 2 dependecy injection in the rest of my application I was wondering if there's a way to do that, is it possible to do the dependency injection dinamically? can I indicate somehow a method or something to pick up the correct implementation at each moment? For the backend I'm using spring core, so a way to do that with the spring context would work to.

I'm using Annotations for everything (@Autowired for Spring, @ManagedProperty for JSF).

EDIT: The project will be deployed on a Tomcat server.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
parranz
  • 223
  • 1
  • 3
  • 11

1 Answers1

2

I suggest you to use CDI in your JSF project, you can then use programmatic injection. You should start with adding CDI Qualifiers to your interface implementations (you will basically create custom annotation for each implementation - tutorial). Then you can use something like

@Named //similar to ManagedBean
@RequestScoped
public Bean {

    @Inject
    @Any
    Instance<YourInterface> yourInterface;

    public void someMethod() {
         if(someCondition) {
             InterfaceImpl impl = yourInterface.select(new SomeOfYourQualifiers()).get();
         }
    }     
}

Source

Also you you don't have to use Autowired in favour of Inject. I am also sure that there is some Spring way how to to this but I will leave that to some Spring expert here:-)

EDIT

According to this answer is really possible to run CDI on Tomcat. You will also find some tutorials like this one. And Spring approach could be using AutowireCapableBeanFactor but as I say, I don't know Spring much so it's just a wild gues:-)

Community
  • 1
  • 1
Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
  • 1
    Thanx for the answer! I can't however use CDI, we are only allowed to use Tomcat 6, and as far as I know it doesn't support CDI :(. – parranz Apr 16 '13 at 14:03
  • Hi, still can't change it to CDI, the project is already too big and we don't have enough time :(. I'll wait and see if there's a way to do it with javax.faces.bean and if it doesn't I'll try AutowireCapableBeanFactory, it really looks like what we need. Thank you very much!! – parranz Apr 17 '13 at 16:41