-->

How to inject one @Named bean in other @Named bean

2020-07-20 03:50发布

问题:

I have the following code:

@Named
@RequestScoped
public class SearchBean{
    private String title;
    private String author;
    // .... getters and setter s
}

In search.xhtml I have:

<h:inputText value="#{searchBean.title}" />
<h:commandButton action=#{srchUI.action}"/>

And I have also the following ControllerBean:

@Named("srchUI")
@RequestScoped
public class SearchUIController {
    public String action(){
        // ...
    }
}

I want to access the SearchBean.title in action() method... how to do it? How to inject this bean in my UI Controller?

回答1:

Use @Inject.

@Named("srchUI")
@RequestScoped
public class SearchUIController {

    @Inject
    private SearchBean searchBean;

    public String action(){

    }

}


回答2:

public class SearchUIController {

    @ManagedProperty(value = "#{searchBean}")
    private SearchBean searchBean;

    // .. setters and getters for the searchBean
}

Getters-setters are necessary.



回答3:

Use @Inject and add Get and Set methods on your injected bean!

@Named(value = "postMB")
@SessionScoped
public class PostMB{
   // inject comments on your posts
   @Inject
   private CommentMB commentMB;


   /* ADD GET and SET Methods to commentMB*/
   public CommentBM getCommentMB(){return this.commentMB;}
   public void setCommentMB(CommentMB newMB){this.commentMB = newMB;}
}


@Named(value="commentMB")
@RequestScoped
public class CommentMB{
  ....
}


标签: jsf-2 cdi