Better pattern for @Autowired

Just ran across this in a video about Spring Boot by Frank Moley and I thought it deserved a callout.

When creating your Beans (e.g. Controller), you can either:

@RestController() public class ItemController { @Autowired; private ItemService itemService;

Or you can do this:

@RestController() public class ItemController { private final ItemService itemService; @Autowired; public ItemController(ItemService itemService) { this.itemService = itemService }

Both work, but the second one makes JUnit testing way easier. The first one @Autowires the actual field, and is really hard to isolate for test. The second one lets the field stay POJO, and @Autowires the constructor. Both are Spring friendly, but only the second one is JUnit friendly.

This entry was posted in Software Project, Uncategorized. Bookmark the permalink.