在Springboot中获取存储库对象为空

时间:2019-03-17 19:15:08

标签: java spring-boot dependency-injection

我的项目结构如下

https://i.stack.imgur.com/CYXND.png

我的代码文件如下

DemoApplication.java

ctx := response.Request.Context()
// fetch values, check for cancellation, etc

NewCarRepository.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");
    }

}

NewCar.java

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

}

CarListGrabber.java

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

即使我使用了@Repository注解,@Service我在服务中也得到了空的存储库对象。

1 个答案:

答案 0 :(得分:1)

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

CarListGrabber grabber = new CarListGrabber();

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

@Autowired
CarListGrabber grabber;