Video in progress

Strong Junior 🌱 Spring

Why is field injection (@Autowired private ...) not recommended?

Dependencies get hidden, fields can't be final, and you can't create the object normally in a test without Spring. You also stop noticing when the class has grown too big.

📖 Answer

@Service
public class ReportService {
    @Autowired private UserRepository users;
    @Autowired private OrderRepository orders;
    @Autowired private MailSender mail;
}

The thing that hurts most is testing. If you do new ReportService(), all three fields are null. To plug in mocks you need reflection, or you end up starting the whole Spring context.

The rest are smaller but real: the fields aren't final, and looking at the class from the outside you can't tell what it needs. One more point: when you see 9 parameters in a constructor, you immediately think "this class does too much". With fields, that doesn't jump out at you.

In test classes (@Autowired MockMvc mvc) field injection is fine — none of these problems matter there.