Temperate phages infect bacteria by injecting their DNA into bacterial cells, where it becomes incorporated into the host genome as a prophage. In the genome of Bacillus subtilis 168, an active prophage, SPβ, is inserted into a polysaccharide synthesis gene, spsM. Here, we show that a rearrangement occurs during sporulation to reconstitute a functional composite spsM gene by precise excision of SPβ from the chromosome. SPβ excision requires a putative site-specific recombinase, SprA, and an accessory protein, SprB. A minimized SPβ, where all the SPβ genes were deleted, except sprA and sprB, retained the SPβ excision activity during sporulation, demonstrating that sprA and sprB are necessary and sufficient for the excision. While expression of sprA was observed during vegetative growth, sprB was induced during sporulation and upon mitomycin C treatment, which triggers the phage lytic cycle. We also demonstrated that overexpression of sprB (but not of sprA) resulted in SPβ prophage excision without triggering the lytic cycle. These results suggest that sprB is the factor that controls the timing of phage excision. Furthermore, we provide evidence that spsM is essential for the addition of polysaccharides to the spore envelope. The presence of polysaccharides on the spore surface renders the spore hydrophilic in water. This property may be beneficial in allowing spores to disperse in natural environments via water flow. A similar rearrangement occurs in Bacillus amyloliquefaciens FZB42, where a SPβ-like element is excised during sporulation to reconstitute a polysaccharide synthesis gene, suggesting that this type of gene rearrangement is common in spore-forming bacteria because it can be spread by phage infection.