在哪些类中允许在Spring Boot应用程序中使用@Autowired?

时间:2017-09-21 10:57:51

标签: java spring spring-boot spring-data-jpa

以下代码段在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;
   }

}

为什么这不起作用?是否有可能使这个工作,如果是这样的话?

1 个答案:

答案 0 :(得分:3)

您必须@Autowire BetfairFacade才能使存储库注入正常工作。如果像您一样手动实例化,那么Spring不会将其视为托管bean。

@Controller
public class MainController {

    @Autowire
    private BetfairFacade client;