Most of the school's 400 students escaped after someone sounded a fire alarm. Police rescued 28 students and two teachers who had holed up inside the school in panic, as helicopters whirred overhead.
The assailant, believed to be about 20 years old, ended the rampage by killing himself, making the death toll in the rampage four, police said.
Several other people were wounded, including a teacher who was hospitalized with a gunshot wound to the cheek. No students were hurt, police said.
Unsure if the man was still inside, police sharpshooters ringed the school in Freising, about 25 miles north of Munich, and anxious parents gathered outside or in gymnasiums.
Police commandos who combed the school discovered the suspected assailant's body several hours later. He had killed himself, Bavarian police spokesman Armin Ganserer said.
"We heard two explosions and then there was a fire alarm. We went out, but we though it was a false alarm," said Mike, an 11th-grader who gave only his first name. "We found out only gradually what had happened."
Workplace and school shootings are rare in Germany, even though crime has risen in recent years.
The rampage began when the assailant walked into a small factory that makes home furnishings in the town of Eching at about 8 a.m. and shot his former boss and a foreman, ages 38 and 40, with a "heavy-caliber gun," police spokesman Hans-Peter Kammerer said. One man died on the spot, the other shortly afterward.
The company had fired the young man in the last few weeks, police said, though the reasons were unclear.
After killing his co-workers, police said the gunman went to the school about 12 miles away in Freising — apparently by commuter train — where he opened fire and seriously wounded the principal, who later died. He set off two homemade pipe bombs.
Several other people, excluding students, were injured at the school, police said.
The school specializes in business, and its students range in age from about 12 to 18.
©MMII The Associated Press. All Rights Reserved. This material may not be published, broadcast, rewritten, or redistributed