Reputation: 2471
I have a simply web service using @PostConstruct
and @PreDestory
annotations.
@PostConstruct
private void init() {...} //initialize some database connection
@PreDestroy
private void release() {...} //release data base resources
then a client will call some web methods to do some database operations. I did a simply testing by setting break points in the code. The @PostConstruct
works fine. but @PreDestroy
method never get called.
I thought @PreDestroy
will always get called when a client finish calling a web method since web service is stateless by nature. So in the end, the instance is always destroyed and before that, my release method should be called? Is this a correct understanding?
But after reading some online resources, i got confused. some says @PreDestroy
will be called when it's un-deployed?
Upvotes: 2
Views: 3402
Reputation: 5569
@PreDestroy
is only called when the application server decides to reduce the size of the Method-Ready pool - i.e. it determines it doesn't need to keep as many instances of your @WebService @Stateless
session bean around. It doesn't get called after each invocation of your @WebMethod
(and @PostConstruct
is only called when a new instance is added to the Method-ready pool, not necessarily before each web method invocation).
If you have logic you need called before and after each method invocation you could do it as follows:
@AroundInvoke
public Object intercept( InvocationContext ctx )
{
try
{
init();
return ctx.proceed();
}
finally
{
release();
}
}
This method can be added to your @WebService
bean or as a separate class using @Interceptors
Upvotes: 7