Sometimes it's fairly easy to tell when David is writing about a particular event such as
לדוד בשנותו את טעמו לפני אבימלך
At other times it's less obvious, but you get a 'lightbulb moment' when someone points it out, e.g. Malbim says that Psalm 30 is about David Hamelech's teshuva being accepted after the sin with Batsheva. Are there any commentaries on tehillim, or on Shmuel for that matter which discuss chapters of tehillim in light of the events that inspired them?