I think Enthuware's answer to this question is incorrect.
The explanation of the first and second answers of the question are: "A stateless session bean cannot access resource managers in a @PostConstruct method." and "A stateless session bean cannot access resource managers in @PostConstruct or @PreDestroy methods."
I created an example on github doing the same thing that's in the example, doing a jndi lookup of another stateless session bean on @PostConstruct and @PreDesktroy methods, and both ways worked.
The example is on
https://github.com/andreiribas/ejb31-jn ... t-example/
In this project, there is a singleton bean, Mainclass. It gets a reference of ResourceDependencyLocator business interface, and its implementation is the stateless session bean ResourceDependencyLocatorBean class.
In ResourceDependencyLocatorBean class, it has a @PostConstruct method, and in this method it uses JNDI to get a reference to the ResourceDependency, and this class is another stateless session bean.
Some code of the classes, the complete code is on github:
//Main Class
@Singleton
@Startup
public class Main {
private Logger LOGGER;
@EJB
private ResourceDependencyLocator resourceDependencyLocator;
@PostConstruct
public void start() {
this.LOGGER = Logger.getLogger(Main.class);
LOGGER.debug(String.format("Resource Dependency message is: %s.", resourceDependencyLocator.locate().getMessage()));
}
}
....
//ResourceDependencyLocatorBean class
@PostConstruct
public void setUp() {
this.LOGGER = Logger.getLogger(ResourceDependencyLocatorBean.class);
try {
InitialContext ctx = new InitialContext();
LOGGER.debug(String.format("ejbJndiName is %s.", ejbJndiName));
this.resourceDependencyInstance = (ResourceDependency) ctx.lookup(ejbJndiName);
} catch(Exception e) {
throw new EJBException(e.getMessage());
}
}
@PreDestroy
public void tearDown() {
try {
InitialContext ctx = new InitialContext();
LOGGER.debug(String.format("Looking up ResourceDependency instance again before destroying this bean. The Dependency Message returned is: %s.", ((ResourceDependency) ctx.lookup(ejbJndiName)).getMessage()));
} catch(Exception e) {
throw new EJBException(e.getMessage());
}
}
According to Enthuware's answer, this should not work, but it does, it returns the right object in the @PostConstruct method and I call another method on it. It returns OK without any exceptions.
I'm testing it using Junit unit tests, and also deploying the war file in an embedded Glassfish V3.2 using maven.