The 49ers have agreed to terms with former Tampa Bay quarterback Josh Johnson on a two-year contract, according to a league source.

Johnson (6-3, 205), who played for 49ers coach Jim Harbaugh for three seasons at the University of San Diego, has made five starts in his four-year career, throwing five touchdowns, 10 interceptions and compiling a 57.7 passer rating. Johnson will presumably compete with Colin Kaepernick, a second-round pick in the 2010 draft, for the backup spot behind Alex Smith.

Johnson visited the 49ers today after previously taking a free-agent trip to Washington. In July, during the NFL lockout, Johnson openly talked about playing for the 49ers even as he had a year left on his contract with the Buccaneers.

“I’d get to come home, be with my family, play for a coach that changed my life and play for a team that I grew up loving,” Johnson said to The Chronicle.

The 49ers have four quarterbacks on the roster: Smith, Kaepernick, Johnson and Scott Tolzien, who will be entering his second NFL season. Tolzien, an undrafted free agent, was inactive for all 16 games last year.