以下代码段在Spring Boot 1.5.7应用程序中有效。
@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;
}
}
以下代码段不起作用,因为当我尝试在eventtypeRepository
中实例化BetfairFacade
时,该字段仍为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;
}
}
为什么这不起作用?是否有可能使这个工作,如果是这样的话?
答案 0 :(得分:3)
您必须@Autowire
BetfairFacade
才能使存储库注入正常工作。如果像您一样手动实例化,那么Spring不会将其视为托管bean。
@Controller
public class MainController {
@Autowire
private BetfairFacade client;