2

The following code snippet works in a Spring Boot 1.5.7 application.

@Controller
public class MainController {

    @Autowired
    private EventtypeRepository eventtypeRepository;

    private BetfairFacade client = new BetfairFacade();

    @GetMapping(path="/update")
    public @ResponseBody int updateBetfair() {
        return client.updateBetfair(eventtypeRepository);
    }

}



public class BetfairFacade {

public BetfairFacade() {
}

public int updateBetfair(EventtypeRepository eventtypeRepository) {
    int out = 0;

    Eventtype bfT = new Eventtype();
    bfT.setEventtype("foo");
    bfT.setName("bar");
    eventtypeRepository.save(bfT);

    return out;
    }

}

The following snippet does NOT work because when I try to instantiate eventtypeRepository in BetfairFacade the field remains null.

@Controller
public class MainController {

    private BetfairFacade client = new BetfairFacade();

    @GetMapping(path="/update")
    public @ResponseBody int updateBetfair() {
        return client.updateBetfair();
    }

}



@Component
public class BetfairFacade {

   @Autowired
   public EventtypeRepository eventtypeRepository;


   public BetfairFacade() {
   }

   public int updateBetfair() {
     int out = 0;

     Eventtype bfT = new Eventtype();
     bfT.setEventtype("foo");
     bfT.setName("bar");
     eventtypeRepository.save(bfT);

     return out;
   }

}

Why does not this work? Is it possible to get this working, if so how?

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
nilo de roock
  • 4,077
  • 4
  • 34
  • 62
  • I actually read that question plus its answers but did not help me as much as the very precise custom answer I received here. – nilo de roock Sep 21 '17 at 12:22

1 Answers1

3

You have to @Autowire the BetfairFacade in order for the repository injection to work. If you instantiate manually like you did, spring will not treat that as a managed bean.

@Controller
public class MainController {

    @Autowire
    private BetfairFacade client;
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63