In your Apache config file, set it up like:
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
# real server configuration
</VirtualHost>
Now, the first <VirtualHost>
will redirect all non-www traffic to the second <VirtualHost>
configuration.