I believe that the text indicates that David wrote it in a reflectory fashion. In the annotation, the noun "טַ֭עְמוֹ" "his behavior" is the key to this. This noun is also used in 1 Samuel 21:14. The interesting thing about this noun is that it can also mean "taste", e.g.
"אִם־יֶשׁ־טַ֝֗עַם בְּרִ֣יר חַלָּמֽוּת׃"
"or is there any taste in the white of an egg?" (KJV) (ESV says: "or is there any taste in the juice of the mallow"). Job 6:6b
When we look look farther along in the psalm to verse 8, we see the verb טַעֲמ֣וּ which is a command to "taste". "טַעֲמ֣וּ וּ֭רְאוּ כִּי־טֹ֣וב יְהוָ֑ה אַֽשְׁרֵ֥י הַ֝גֶּ֗בֶר יֶחֱסֶה־בֹּֽו׃" "Oh, taste and see that the LORD is good! Blessed is the man who takes refuge in him!" (ESV).
So if we read the annotation as "Of David, when he changed his taste before Abimelech..." or if we at least see that there is some wordplay going on, then this opens the historical connection up for us. It seems to me that the whole psalm is focused on his repentance from his actions and attitude when he feigned madness.
Ps. 34:
1I will bless the LORD at all times;
his praise shall continually be in my mouth.
2My soul makes its boast in the LORD;
let the humble hear and be glad.
3Oh, magnify the LORD with me,
and let us exalt his name together! Psalm 34:1-3 ESV
David may not have been boasting himself, but in 1 Samuel 21, Achish's servants were reminding Achish that the Israelites had been boasting about David's exploits in battle. They had been exalting David's name. David hadn't acknowledged God's help in 1 Samuel 18, and as a result of the people boasting about him, Saul became jealous (which led to David fleeing to Philistia). David is acknowledging that he should have boasted in YHWH, and he is stating that he does and will do so since his repentance.
4I sought the LORD, and he answered me
and delivered me from all my fears.
5Those who look to him are radiant,
and their faces shall never be ashamed.
6This poor man cried, and the LORD heard him
and saved him out of all his troubles.
7The angel of the LORD encamps
around those who fear him, and delivers them. Psalm 34:4-7 ESV
David had been ashamed of how he acted because he didn't look to God for deliverance from Achish, but rather devised his own scheme to escape--feigning madness--which relied on his own cunning rather than a trust of God. David, in his fear, had forgotten to look to God for rescue. The testimony to YHWH's deliverance suggests that David is writing this after a significant amount of time has passed. He has repented of not seeking YHWH for deliverance and he has experienced that deliverance to a remarkable degree--he has been delivered from all his fears.
8Oh, taste and see that the LORD is good!
Blessed is the man who takes refuge in him!
9Oh, fear the LORD, you his saints,
for those who fear him have no lack!
10The young lions suffer want and hunger;
but those who seek the LORD lack no good thing. Psalm 34:8-10 ESV
Here we see the key to the historical connection. David had changed his "taste" before Achish. He had taken refuge in Philistia from Saul, and now he had to take refuge from Achish by feigning madness. In his changing his taste due to fear of man, he had really suffered want--the want of assurance of safety. David exhorts those listening to the psalm to taste the goodness of YHWH. In v.8, YHWH is good. In v.10, those who seek YHWH lack no good. "[T]hing" is implied. So those who seek YHWH find Him and are content with His goodness. Even though it seemed like David had to solve his own problem in Gath, if he had sought YHWH, he would have been satisfied in YHWH Himself, even if he had been killed by Achish.
11Come, O children, listen to me;
I will teach you the fear of the LORD.
12What man is there who desires life
and loves many days, that he may see good?
13Keep your tongue from evil
and your lips from speaking deceit.
14Turn away from evil and do good;
seek peace and pursue it. Psalm 34:11-14 ESV
Although it might have seemed at first possible that David had cried out to God for deliverance at the time when he was in danger from Achish (see vv. 4-7), this section disproves that possibility. David had lived by deceit when he was in Philistia. Out of love for his own life, he had tricked Achish into thinking he was no threat. In these verses of Psalm 34, David declares that the way to live long is to live honestly and thus to live in the fear of YHWH. It seems likely that David wrote this Psalm even after he had escaped to the cave at Adullam (1 Samuel 22), since David fled to Philistia a second time and once again lived deceptively there by suggesting that he was raiding Southern Judah 1 Samuel 27 ESV, when he was actually raiding people south of Judah (see John Gill's comments on 1 Samuel 27:10). It is possible, however, that David wrote this psalm in repentance, and then sinned with deception again, but this doesn't seem likely to me with the addressing of his children in v. 11. Rather I think he is telling his children about his folly in the past and teaching them the right way to go in this psalm.
15The eyes of the LORD are toward the righteous
and his ears toward their cry.
16The face of the LORD is against those who do evil,
to cut off the memory of them from the earth.
17When the righteous cry for help, the LORD hears
and delivers them out of all their troubles.
18The LORD is near to the brokenhearted
and saves the crushed in spirit."
David attests to YHWH's faithfulness in answering the prayers of His people and alludes to the destruction of Achish. In v.18 David recounts how YHWH relates to those who are repentant. This seems to be further confirmation that the psalm was written a considerable time after the event since the repentance in view doesn't have an immediacy to it. The third person in David's account (the brokenhearted) could be to emphasize God's mercy in this story rather than having the focus on David and how he messed up.
19Many are the afflictions of the righteous,
but the LORD delivers him out of them all.
20He keeps all his bones;
not one of them is broken.
21Affliction will slay the wicked,
and those who hate the righteous will be condemned.
22The LORD redeems the life of his servants;
none of those who take refuge in him will be condemned.
David understands that God's people are persecuted and live a difficult life, but he continues to point to YHWH's deliverance. I believe that v.20 is the final proof that David wrote this psalm (since the annotation could perhaps be read as a dedication "to David"). Although there is the apparent historical application to David that he escaped from Achish in one piece, verse 20 is also referenced/quoted in John 19:31-36 ESV. However, the question is whether John has specifically Psalm 34:20 in mind, or whether he is instead thinking of Exodus 12:46 and/or Numbers 9:12?
Regarding the Passover, Exodus 12:46 ESV and Numbers 9:12 ESV command that its bones not be broken.
Though I disagree with their rejection of Psalm 34:20 being quoted by John (which I will account for below), this Messianic Jewish website provides some interesting explanation of how Jesus is the Passover lamb whose bones were not broken.
John 19:36 SBLGNT uses the identical 3rd sg future passive verb συντριβήσεται that Psalm 34:20 (21 LXX) does, whereas Exodus 12:46 uses the 2nd pl future active συντρίψετε and Numbers 9:12 uses the 3rd pl fut act συντρίψουσιν.
κύριος φυλάσσει πάντα τὰ ὀστᾶ αὐτῶν,
ἓν ἐξ αὐτῶν οὐ συντριβήσεται. Ps. 34:21 LXX
καὶ ὀστοῦν οὐ συντρίψετε ἀπ' αὐτοῦ. Ex. 12:46c LXX
καὶ ὀστοῦν οὐ συντρίψουσιν ἀπ' αὐτοῦ Num. 9:12b LXX
Ὀστοῦν οὐ συντριβήσεται αὐτοῦ Jn 19:36 SBLGNT (the Byzantine text has ἀπ' αὐτοῦ)
Source for the LXX verses: Navigable LXX, which unfortunately cannot link to specific books, chapters or verses
As can be readily seen, John's construction is not a word-perfect quotation of any of the three. The construction most closely parallels the two verses from Moses, but the verb is that used by (the translators of) David. It seems the best answer for this puzzle is that John is drawing all three texts together (though perhaps making his own translation) to show forth Jesus as God's Anointed One who was also the Passover Lamb.
In at least partial support of this view, G.K. Beale in his Handbook of the New Testament's Use of the Old Testament says of Psalm 34:20,
It would seem that the Psalm verse makes use of the Exodus/Numbers text and applies it to David as a righteous sufferer and that John 19:36 has all of these texts in mind, the Psalm text being part of the basis for typologically applying the Exodus/Numbers Passover Lamb passages to Jesus (and note the repeated reference to the Passover in John [13 times, three of which are in 18:28, 39, and in 19:14]). The Psalm 34 passage about David is also applied typologically to Jesus.
In conclusion, the significance of Psalm 34:20 being applied to Jesus makes it practically certain that David was the author of it, since David was God's anointed one and his life foreshadowed Christ. Though the historic fulfillment of the righteous one's bones not being broken did play out in David's life, it is a stretch to expect that a generic righteous man is in view--many of God's people have had their bones broken. Furthermore, David's spirit was crushed/pulverized in v. 18, but his bones were not. It pleased the Father to crush the Son (Is. 53:10). The same root is used in both cases. The fullest application of Psalm 34:20 is to Jesus in his work as mediator, who had his spirit crushed for the sins of his people, but his bones were not broken.