The problem involves two concepts -
1. the conservation of linear momentum.
2. the conservation of energy .
But first we say that the system is our ball + barrel ....now as there is no external force acting on the system ( no friction) so we can conserve the linear momentum :
mu = (m+ M)v ..............................................................(1)
( letting the final velocity of the system be v)
1/2 mu2 = 1/2 (m+M) v2 + Z .........................................(2)
(letting the energy store in spring be denoted by Z)
so putting the values from eqn 1 to eqn 2 we can get ...
Z = 1/2 mu2 [ M /m+M ]
or Z / (K.E)i = M/M+m