Bar lines cancel any changes within a measure. The natural for the G in the 2nd measure doesn't really have or need to be there [it is a courtesy natural - a reminder].
The natural for the D in the 4th measure is necessary. We already had a D# in the measure. The D has been previously modified [sharped] within the same measure, so we need the natural to indicate that a D natural should be sounded.