tags:

views:

219

answers:

2

In spring I often find myself utilizing the init-method & destroy-method attributes on beans. I'm curious about the contract of these methods. The init-method attribute seems to be called post construction and after all properties have been set. My question is if destroy-method has the same contract. If a setter throws for whatever reason, and the object doesn't have all its properties set, spring won't call the init-method, but I can't find any documentation about spring calling the destroy-method in this situation.

If it does obviously checks for null have to be in place, I'm curious what others do in this situation.

+2  A: 

I did a simple test and I found out that in case of a setter throwing an exception both the init and the destroy methods won't be called.

I believe that this is the logical thing to do. A setter shouldn't be allowed to fail - if it does, there is nothing the framework can do to help you. The only reaction to this kind of error is to correct the setter. So I think that your question is irrelevant. Half injected objects shouldn't be allowed.

If you know that a setter could throw an Exception, you should catch it and set a reference to null or do whatever else is appropriate.

kgiannakakis
+2  A: 

The Spring code of interest here is AbstractAutowireCapableBeanFactory.doCreateBean() (I'm looking at the Spring 3 M4 source, but it should be essentially the same for Spring 2.5). The the last thing this method does is register the bean for disposal, and it only does that if the rest of the method (including instantiation and initialization) succeeds. So if any part of the bean initialization fails, the destroy-method callback won't be invoked.

skaffman