Derivation (magnetic field energy)
First expression
Consider a current $I$ flowing around a fixed circuit $C$. If $I$ is varied, an emf is induced $$ \begin{align*} \mathcal{E} = -\dfd{\mathcal{F}}{t} = -L\dfd{I}{t}. \end{align*} $$ In a small time interval $δt$, a charge $δq = I\,δt$ flows around $C$, and the work done on it by Lorentz force is $$ \begin{align*} δW = \mathcal{E}\,δQ = -LI \dfd{I}{t} \delta t. \end{align*} $$ So the rate at which work is done by the current on the EM field is $$ \begin{align*} -\dfd{W}{t} = LI \dfd{I}{t} = \dd{t}\left(\frac{1}{2}LI^2\right). \end{align*} $$
So building up the current from $0$ to $I$ takes energy $$ \begin{align*} U ={}& \frac{1}{2}LI^2 \\ ={}& \frac{1}{2} I\mathcal{F} \\ ={}& \frac{1}{2} I\int_{C} \v A\cdot \d \v x \\ ={}& \frac{1}{2}\int_{V} \v J\cdot \v A \d^3\v x. \end{align*} $$
Second expression
Using (M4), $$ \begin{align*} U = \frac{1}{2μ_0} \int_{V} (∇\times \v B)\cdot \v A \d^3 \v x \end{align*} $$ and applying the identity $$ \begin{align*} ∇\cdot (\v B \times \v A) = (∇\times \v B)\cdot \v A - (∇\times \v A)\cdot \v B \end{align*} $$ and the divergence theorem, we get $$ \begin{align*} U = \frac{1}{2μ_0}\left(\int_{\partial V} (\v B \times \v A)\cdot \d \v S + \int_{V} (∇\times \v A)\cdot \v B \d^3\v x\right). \end{align*} $$
Take $V$ to be a ball of radius $R\to \infty$. For a finite current distribution, by the dipole approximation, $|\v A| = O(1/R^2)$ and $|\v B| = O(1/R^3)$ on $\partial v$ as $R\to \infty$ while the area of $\partial V$ is $O(R^2)$. Thus the first term vanishes asymptotically, giving $$ \begin{align*} U = \int_{\R^3} \frac{1}{2μ_0} |\v B|^2 \d^3 \v x \end{align*} $$ because $∇\times \v A = \v B$.