Java 使用@Autowire时使用空指针

Java 使用@Autowire时使用空指针,java,spring-boot,Java,Spring Boot,我想通过(@Autowire)创建一个对象,但不幸的是,这个DAO对象从未创建过,因此引发了Nullpointer异常 这是我的DAO实现: package com.sample.dao.service; @Component public class OrderServiceImpl implements OrderService { private final OrderRepository orderRepository; @Autowired OrderSe

我想通过(@Autowire)创建一个对象,但不幸的是,这个DAO对象从未创建过,因此引发了Nullpointer异常

这是我的DAO实现:

package com.sample.dao.service;

@Component
public class OrderServiceImpl implements OrderService {

    private final OrderRepository orderRepository;

    @Autowired
    OrderServiceImpl(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    @Override
    public void save(Order order) {
        return orderRepository.save(order);
    }
导致Nullpointer异常的类:

package com.sample.dispatcher;

@Component
public class OrderDispatcher  {

    private final OrderServiceImpl orderServiceImpl;

    @Autowired
    public OrderDispatcher(OrderServiceImpl orderServiceImpl) {
        this.orderServiceImpl = orderServiceImpl;
    }

    public void createOrder(Order order) {
        orderServiceImpl.save(order));   //  --> Nullpointer
我的入门课程:

package com.sample;

@SpringBootApplication
@ComponentScan(basePackages = { "com.sample" , "com.webservice"})
@EnableJpaRepositories(basePackages = "com.sample.dao.repository")
public class Application {

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

我认为应该更改构造函数,使其具有参数类型的接口,而不是具体的实现。像这样的-

@Component
public class OrderDispatcher  {

private final OrderService orderServiceImpl;

@Autowired
public OrderDispatcher(OrderService orderServiceImpl) {
        this.orderServiceImpl = orderServiceImpl;
        }

当您在OrderServiceImpl上添加
@组件
符号时,会为该类创建代理,并且它可以通过接口自动连接。

可能您忘记了
@注释
配置。尝试添加此类并扫描实体:EntityScan

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;


@Configuration
@EntityScan("com.sample.model") // Your model package
@ComponentScan(basePackages = { "com.sample" , "com.webservice"})
@EnableJpaRepositories(basePackages = "com.sample.dao.repository")
public class RepositoryConfig {

}

OrderDispatcher依赖于OrderServiceImpl,OrderServiceImpl依赖于OrderRepository。检查OrderRepository是否已正确初始化。在Spring启动时是否有任何错误?是否已注释OrderRepository?