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: , ,

Followers

Pageviews Last 7 Days