我有以下项目结构



我的代码文件如下

DemoApplication.java

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        CarListGrabber grabber = new CarListGrabber();
        grabber.grabCarsWithName("Test");
    }

}


NewCarRepository.java

@Repository
public interface NewCarRepository extends CrudRepository<NewCar, Long> {

}


NewCar.java

@Entity
@Table(name = "new_car_details")
public class NewCar {
    // member variables with default constructor
}


CarListGrabber.java

@Service
public class CarListGrabber {

    @Autowired
    private NewCarRepository newCarRepository;

    // someOtherStuff
}


即使我已使用批注@ Repository,@ Service,但在服务中却获取了空存储库对象。

最佳答案

您要使用以下方法实例化新的CarListGrabber

CarListGrabber grabber = new CarListGrabber();


它不会进行注入,您也需要注入grabber,例如:

@Autowired
CarListGrabber grabber;

10-06 13:00