Thought to have come from Robert Herrick's poem Mad Maid's Song, 1648.
Ah! woe is me, woe, woe is me! Alack and well-a-day! For pity, sir, find out that bee Which bore my love away. I'll seek him in your bonnet brave, I'll seek him in your eyes; Nay, now I think they've made his grave I' th' bed of strawberries.
The first citation that uses the precise phrase is in Thomas De Quincey's Coleridge & Opium-eating, 1845:
"John Hunter, notwithstanding he had a bee in his bonnet, was really a great man."
De Quincey makes no attempt to explain the line, which would have sounded rather odd if heard for the first time out of any context. We can surmise that he would have expected his readers to be familiar with it, and that this may well not be the first appearance of it in print.