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")This is an application bug and nothing is wrong with the application server. The right way to validate injection fields is the
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...
}
@PostConstruct
method. In the @PostConstruct
method, all injections are guaranteed to have completed.@Stateless(mappedName="FooBean")Technorati Tags: PostConstruct, JavaEE, Java
public class FooBean implements FooRemote {
@Resource
private SessionContext sctx;
@PostConstruct
private void validate() {
System.out.println("Inside @PostConstruct, Injected SessionContext: "
+ sctx);
}
//business methods...
}