Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Spring Basics Using the MVC Architecture Add a CategoryController

Ricardo Sala
Ricardo Sala
13,390 Points

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;

private final GifRepository gifRepository;

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

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:

public class GifController {
  private final GifRepository gifRepository;

  // Annotate your constructor with 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 :)