Nicely mounting 2x4s to wall
I'd try a few of these keyhole mounting plates:



You'd need to be very precise with screw placement so everything lines up properly.  If you're feeling adventurous, you could chisel or route out a recess so the whole thing is flush against the wall.  You could also mount the plates to the wall at a stud, using sufficiently long screws, and then use smaller screws on the shelf to clip in.

Another alternative would be to drill mostly through the stock, screw directly into the wall, and plug the holes with dowel.