11/16/2007

When to forget about constructors in JavaEE

Sometimes I see people do some sort of validation inside the constructors of a JavaEE component class, like EJB or servlet class. They do this mostly for testing or debugging purpose, but always surprised to see certain fields have not been injected. For example, the following validation in the constructor will shows the SessionContext is null!
@Stateless(mappedName="FooBean")
public class FooBean implements FooRemote {
@Resource
private SessionContext sctx;

//DO NOT DO THIS
public FooBean() {
System.out.println("Inside constructor, Injected SessionContext: "
+ sctx);
if(sctx == null) {
throw new IllegalStateException
("SessionContext not injected! Something is wrong!!");
}
}
//business methods...
}
This is an application bug and nothing is wrong with the application server. The right way to validate injection fields is the @PostConstruct method. In the @PostConstruct method, all injections are guaranteed to have completed.
@Stateless(mappedName="FooBean")
public class FooBean implements FooRemote {
@Resource
private SessionContext sctx;

@PostConstruct
private void validate() {
System.out.println("Inside @PostConstruct, Injected SessionContext: "
+ sctx);
}
//business methods...
}
Technorati Tags: , ,

3 comments:

Данечкин said...

thnx, very simple and clear way to check all the resources was properly initialized

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Vũ Diệu Linh said...

I enjoyed on reading your blog post. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. Please visit my website, Friv 4000 Games is where all the free friv games.
Friv 4000