Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Spring Basics Using the MVC Architecture Add a CategoryController

Field injection is not recommended

This what IDEA says about the @Autowired, and I can't compile it... Can you please take a look? Thks!

@Autowired private final CategoryRepository categoriesRepository;

@Autowired
private final GifRepository gifRepository;


@RequestMapping("/categories")
public String listCategories(ModelMap modelmap) {
    List<Category> allCategories = categoriesRepository.getAllCategories();
    modelmap.put("categories", allCategories);
    return "categories";
}

@RequestMapping("/category/{id}")
public String category(@PathVariable int id, ModelMap modelMap) {
    Category category = categoriesRepository.findById(id);
    modelMap.put("category", category);
    List<Gif> gifs = gifRepository.findByCateogoryId(id);
    modelMap.put("gifs", gifs);
    return "category";
}

}

2 Answers

Field dependency injection could result in a NullPointerException, so it's not considered a best practice.

Here's how to do constructor dependency injection:

@Controller
public class GifController {
  private final GifRepository gifRepository;

  // Annotate your constructor with autowired
  @Autowired
  public GifController(GifRepository gifRepository) {
    this.gifRepository = gifRepository;
  }
}
Rodrigo Castro
Rodrigo Castro
15,652 Points

Hi Ricardo,

The GifRepository field is declared as 'final', so the compiler would expect it to be initialised. Try removing the β€˜final’ word to see if it compiles.

Hope it helps :)