Obviously it's selfishness, but it's a prisoners dilemma where the you just lose if you are the only one training the juniors who then move on to the competitors later.
So motivate them to not move on to competitors. I don't think companies should cynically take it as given that people only last N years, and will leave for greener pastures once they're trained. They're leaving for a reason, so address that reason.
I have quit a dev job exactly one time, when offered a salary the first one wouldn't meet (the HR person straight up told me she didn't understand why they would pay me $80k in the exit interview, this was like 6 years ago). Since the second company pays me well (with benefits), gives me yearly raises, and gives out generous performance based bonuses, I haven't looked for another job since then. And yes, job #2 is often boring.