Yes, transit purposes you can
- for a week holiday in Spain beforhand would probably not be considered transit
but changing a plane in Spain to Germany would pose no problem with a D-Visa.
Border Code Article 6
- Entry conditions for third-country nationals
- By way of derogation from paragraph 1:
(a) third-country nationals who do not fulfil all the conditions laid down in paragraph 1 but who hold a residence permit or a longstay visa shall be authorised to enter the territory of the other Member States for transit purposes so that they may reach the territory of the Member State which issued the residence permit or the long-stay visa, unless their names are on the national list of alerts of the Member State whose external borders they are seeking to cross and the alert is accompanied by instructions to refuse entry or transit;