dev@glassfish.java.net

Resource Injection and Lifecycles

From: Jacob Hookom <jacob_at_hookom.net>
Date: Mon, 15 Aug 2005 01:35:44 -0500

I was looking at @Resource in relation to lifecycles represented in the
web tier. Outside of the EJB spec, there's opportunity to cause
conflicts between gained resources and the lifecycles of application or
session scoped beans. On top of that, gained resources aren't often
Serializable, so assigning them to clusterable instances may cause
issues for developers.

The code within InjectionManagerImpl does a fine job of injecting
resources, but they are set as literal instances on the member
variables. This leaves you with shared DataSources or JMS entities that
would live beyond their expected lifespans with traditional
InitialContext use.

Really, what is the purpose of @Resource? To shortcut the lookup against
the InitialContext-- not to retain references to stateless resources.
To me, there seems to be a impendance mismatch under the current
implementation.

Would it be suitable to instead assign serializable, proxy references to
Fields/Methods such that any time they are accessed, they go back to the
InitialContext?

public class ResourceInvocationHandler implements InvocationHandler,
Serializable {

private final String envName;

public ResourceInvocationHandler(String envName) {
  this.envName = envName;
}

public Object invoke(Object proxy, Method method, Object[] args) throws
Throwable {
  InitialContext namingCtx = new InitialContext();
  Object base = namingCtx.lookup(envName);
  return method.invoke(base, args);
}
}

Granted there would need to be better exception handling, but this
basically outlines support for traditional, stateless resources,
independent of the client beans' lifecycle.

-- 
Jacob Hookom - Minneapolis
--------------------------
http://hookom.blogspot.com