18 January 2010

Calling session beans on JSF Managed bean's start up

One situation may occurs is that you need to call some session bean method on some JSF page's start up.

If you try to put the code that calls the injected EJB session bean's method in your JSF request-scoped Managed bean constructor, you will get a NullPointerException as the Injection occurred after making an instance of the managed bean.

The solution is that to provide a @PostConsruct method and put your EJB calling code in.
@PostConsruct is supported in JSF1.2 and if you running your JSF Application in an Application Server (example JBoss)

So, Here's the sequence the managed bean instance is created in:

Calling manged bean constructor => Injecting Session bean (if any) => calling PostConstruct method(s) (if any)

Here's an example:

public class ShowArticleBean {

@EJB(name="SimpleWiki/ArticleManagementBean/local")
private ArticleManagement articleMgmt;

public ShowArticleBean() {
System.out.println("In Constructor : " + articleMgmt);

}

@PostConstruct
public void construct() {
System.out.println("In PostConsruct : " + articleMgmt);
}


And here's the output :

04:51:29,546 INFO [STDOUT] In Constructor : null
04:51:29,547 INFO [STDOUT] In PostConsruct : ArticleManagementBean

12 comments:

Jigar said...

hey here if i use post construct then it will be called after initilization of bean,
but what i want is i need to call a method on load time of application which is going to use fully initilized context ,
how to do this.. ?
any idea?
thanks in advance

Jigar said...

in jSF1.2

Mohammed Hewedy said...

Hey Jigar,
I think you mean you want to call some method one one of your beans but you need to have your bean initialized in terms of managed properties, if this correct, try to use the following code snippet :

FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ValueExpression vexpression =
elFactory.createValueExpression(context.getELContext(), "#{backingBean}", org.daz.BackingBean.class );
org.daz.BackingBean myBackingBean = vexpression.getValue();

Jigar said...

getValue() method takes a parameter..

Mohammed Hewedy said...

Yes, you are right.
Try to pass "context.getELContext()" and this will work for you :)

Mohammed Hewedy said...

I hope this is what you seek :)

Jigar said...

context is null friend @ initilization time..

Mohammed Hewedy said...

I hope this help you :
http://www.oracle.com/technology/products/jdev/tips/fnimphius/advancedeltechniques/advancedeltechniques.html?_template=/ocom/print

Helen said...

Nice and clear review. But I think beginners still need the basics to fully grasp what's going on here.

Helen Neely

Jigar said...

:)

Mohammed Hewedy said...

@Helen :
I am still beginner too :)

Bri said...

very helpful blog, glad i stumbled upon this one. thanks for posting this :D
check out my blog sometime http://www.retrostruggle.com