[jboss-user] [EJB 3.0] - Re: @EJB Injection in JSF Managed Bean

klejs do-not-reply at jboss.com
Thu Nov 30 15:31:27 EST 2006


If you don't want your code full of EJB dependent code you can use a VariableResolver instead to "inject" your EJBs into your Managed Beans. It would look something like this:

public class SessionBeanVariableresolver extends VariableResolver {
  | 
  |    private Context context;
  | 
  |    protected final VariableResolver resolver;
  | 
  |    public SessionBeanVariableResolver(VariableResolver resolver) {
  |       super();
  |       this.resolver = resolver;
  |       try {
  |          context = new InitialContext();
  |       }
  |       catch(NamingException e) {
  |          // handle exception
  |       }
  |    }
  | 
  |       
  |    @Override
  |    public Object resolveVariable(FacesContext context, String name)
  |       throws EvaluationException {
  | 
  |       // Return if object found with regular resolver
  |       Object result = resolver.resolveVariable(context, name);
  |       if(result != null) {
  |          return result;
  |       }
  |       
  |       try {
  |          result = context.lookup(name);
  |       } 
  |       catch (NamingException e) {
  |          // handle exception		
  |       }
  |       
  |       return result;
  |    }
  | }
  | 

In your backing beans you should have a setter for the EJB like this:

public Class MyManagedBean() {
  | 
  |    private MyEjbInterface bean;
  | 
  |    public void setMyEjbInterface(MyEjbInterface bean) {
  |       this.bean = bean;
  |    }
  | }

And finally in your faces config you should have an entry for your variable resolver:

<variable-resolver>my.package.SessionBeanVariableResolver</variable-resolver>

and on you managed bean you should set a managed property like this:

<managed-bean>
  |    <managed-bean-name>MyManagedBean</managed-bean-name>
  |    <managed-bean-class>my.package.MyBean</managed-bean-class>
  |    <managed-bean-scope>request</managed-bean-scope>
  |    <managed-property>
  |    <property-name>myEjbInterface</property-name>
  |       <value>#{path_to_ejb}</value>
  |    </managed-property>
  | </managed-bean>

View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=3990206#3990206

Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=3990206



More information about the jboss-user mailing list