The true obstacle to King David building the Temple - as Rav Sa’adia Gaon explains - was not an ethical-spiritual deficiency connected to his participation in wars, but rather the need for him to dedicate his life exclusively to the labor of war. Changing gears in his old age and dedicating his life to a different labor altogether was not what Hashem had in mind for him. This would be the life-project not of King David, but of his young son, who would sanctify his entire life to building a house for Hashem (Rasag, Targum Ha-Tanach Le-Arvavit Le-Divrei Ha-Yamim 129:9).
One must understand that the building of the Temple is the final, climactic step and not the beginning. There are three Mitzvot which we are commanded when we enter the Land - building the Kingship of Israel, fighting the war with Amalek, and building the Temple - and they must be performed in this order (Rambam, Hilchot Melachim 1:1-2). Therefore, anyone who is involved in building the Kingship of Israel is also involved in the waging of war, which is necessarily connected to it, as in the words of the Rambam’s title: "Laws of Kings and their Wars". And all of this precedes, and leads to, the building of the Temple.
Anyone who fights the wars of Hashem is involved in the preparation of the Temple. And this is what was said of King David: Although you were not involved in the actual building of the Temple, you nevertheless prepared it by the great wars which you waged, and now your son is able to build it. Our Master Ha-Rav Avraham Yitzhak Ha-Cohain Kook similarly writes: "In building the Temple, as the King said to the prophet Natan: ‘See now, I dwell in a house of cedar, but the Ark of God dwells within a curtain’ (Shmuel 2 7:2), the prophet responds to him with the word of Hashem: ‘Did I speak a word with any of the rulers of Israel, who I commanded as shepherds of my Nation saying, why do you not build me a house of cedar?’ (ibid. verse 7). When the times comes, ‘I have appointed a place for my Nation Israel, and planted them, that they may dwell on it, and be troubled no more, nor will the children of wickedness torment them anymore, as in the beginning’ (ibid. verse 10), then the time will have arrived to build the Temple. Everything that King David, may peace be upon him, did, all the wars that he waged with the enemies of Israel to break the nations of the world from around our neck and to expand the borders of our Land, all of this was a preparation and a readying for the ultimate goal of building the Temple" (Ma’amrei Ha-Re’eiyah vol. 1, pp. 246-247).