The deal comes shortly after the club signed central defender Mehdi Benatia from AS Roma for a reported €25 million.
Alonso, 32, retired from international football on Wednesday and within hours was linked with the Bundesliga champions.
The former Spain international - who has won the World Cup, two European Championships, two Champions Leagues and the Liga title - has made 236 appearances for Real Madrid, who he joined from Liverpool in 2009.
Bayern are looking for short-term cover for central midfielders Martinez and Alcantra, with both Spaniards in different stages of recovery from serious knee injuries.
"This is purely sporting decision because Alonso can instantly help us and boost our quality," Bayern sports director Matthias Sammer said. "He can play top level football for at least two more years."
Real were happy to let Alonso leave for the club managed by former Barca boss Pep Guardiola, with Bayern reportedly giving the Spaniard an annual salary of €10 million.
- Sports & Recreation
- Thiago Alcantara
- Pepe Reina
- Real Madrid
- Juan Bernat