以下代碼片段適用於Spring Boot 1.5.7應用程序。允許在Spring Boot應用程序中使用@Autowired在哪些類中?
@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;
}
}
下面的代碼片段不起作用,因爲當我嘗試在BetfairFacade
實例eventtypeRepository
領域仍然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;
}
}
爲什麼不能正常工作?如果可以的話,是否有可能實現這個目標?
我實際上讀過這個問題及其答案,但並沒有像我在這裏收到的非常精確的自定義答案那樣幫助我。 –