开发者

JSF 2.0 Accessing Application Scope bean from another Bean

开发者 https://www.devze.com 2023-03-07 22:49 出处:网络
I am using jsf 2.0 and I have two bean Navigation (Application Scope ) and Module (Request Scope). I want to use methods of Navigation bean in Module Bean. I am开发者_StackOverflow社区 doing in this w

I am using jsf 2.0 and I have two bean Navigation (Application Scope ) and Module (Request Scope). I want to use methods of Navigation bean in Module Bean. I am开发者_StackOverflow社区 doing in this way In Module Bean

 @ManagedProperty(value = "#{navigationBean}")
    private NavigationBean navigationBean;

But when I am trying to get navigationBean.SomeMethod it is not working as navigation bean is null . How to do this?


The both beans needs to be a fullworthy @ManagedBean. The acceptor should have a public setter method for the injected bean. The injected bean is only available in @PostConstruct and beyond (i.e. in all normal event methods, but thus not in the constructor of the acceptor).

So, this ought to work:

@ManagedBean
@ApplicationScoped
public class Navigation {
    // ...
}

@ManagedBean
@RequestScoped
public class Module {

    @ManagedProperty(value="#{navigation}")
    private Navigation navigation;

    @PostConstruct
    public void init() {
        navigation.doSomething();
    }

    public void setNavigation(Navigation navigation) {
        this.navigation = navigation;
    }

}


I think @ManagedProperty requires a public set method to work.


I got The solution

I have a method in application signature boolean getReadAccess(String role, String module ). If i want to use in another bean then i have to follow these steps

    `javax.el.MethodExpression readAccess;
     javax.el.ELContext elContext = null;
     javax.faces.context.FacesContext context = FacesContext.getCurrentInstance();
     elContext = ((FacesContext) context).getELContext();
     javax.faces.application.Application application = FacesContext.getCurrentInstance().getApplication();
     javax.el.ExpressionFactory expressionFactory = application.getExpressionFactory();
     readAccess = expressionFactory.createMethodExpression(elContext,
            "#{navigationBean.getReadAccess}", Void.class, new Class[] {
                    String.class, String.class });

    //--------Call----------------------------
    return (Boolean) readAccess.invoke(elContext, new Object[] {
                "roleName", "moduleName" });

`

0

精彩评论

暂无评论...
验证码 换一张
取 消