Sunil
Sunil

Reputation: 127

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

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?

Upvotes: 3

Views: 5214

Answers (3)

Miguel Vieira
Miguel Vieira

Reputation: 57

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{
  ....
}

Upvotes: -2

BalusC
BalusC

Reputation: 1109875

Use @Inject.

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

    @Inject
    private SearchBean searchBean;

    public String action(){

    }

}

Upvotes: 4

palacsint
palacsint

Reputation: 28895

public class SearchUIController {

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

    // .. setters and getters for the searchBean
}

Getters-setters are necessary.

Upvotes: -1

Related Questions