I believe this was written before the episode with Bathsheva, simply on the grounds of where this psalm and the one written after David's sin (Psalm 51) are located in the Hebrew Scripture. The tone of Ps. 22 is one of expectation of vindication, the tone of Ps. 51 is God's righteousness vs. David's unrighteousness. I would be so bold as to say that Ps. 22 is prophetic, and refers to Jesus as the Son of David.
I believe this was written before the episode with Bathsheva, simply on the grounds of where this psalm and the one written after David's sin (Psalm 51) are located in the Hebrew Scripture. The tone of Ps. 22 is one of expectation of vindication, the tone of Ps. 51 is God's righteousness vs. David's unrighteousness. I would be so bold as to say that Ps. 22 is at least to some degree prophetic.