This was written while David was on the run from Saul.
David had already been anointed king, but there was a long time before he actually assumed the position. In this Psalm we see that he puts his trust firmly in the Lord, and he trusts the Lord to deal with the difficult and life threatening situation he finds himself in.
David declares that all the good things he has come from the Lord. We can often be deceived in thinking some good thing comes from another source, and so we desert the Lord.
David delights in the godly people in the land. The people we should admire are not the ones the world admires.
Even though David experienced danger, he declares that the he is satisfied with the life that God has assigned to him, and that he believes he is secure. We need to develop this same trust in God.
Fears can come in the night, at those times we should praise the Lord, we should also look to hear the wise voice of the Holy Spirit counselling us. In all situations we should look to the Lord and rely on Him for guidance. Then we will have true security and peace. The Lord will not abandon us, and He has shown us the path of life.
We should remember that David wrote this in the midst of difficulties. If we are facing challenges and trials at the moment, we should ask God to enable us to have joy and peace in the midst of them.