【问题标题】:Cannot inject service in Spring [duplicate]无法在 Spring 中注入服务 [重复]
【发布时间】:2021-04-15 19:41:44
【问题描述】:

我是 Spring / Spring Boot 的新手,并尝试将服务注入到一个类中。虽然我尝试了一些方法,例如@Autowired,服务实例始终为空并抛出“NullPointerException”错误。我不确定是否需要为 DI 注册此类和服务,但据我所知,在类中使用 @Component 或类似注释时会自动注册。我想我错过了一些点,但还没有发现问题。能否请您看一下代码,让我知道问题或缺失点在哪里?

//@Component // I also tried with this, but employeeService is still null
@Data
@EqualsAndHashCode(callSuper = true)
public class EmployeeRequest extends PageableCriteriaRequest {

    @Autowired
    public EmployeeService employeeService;

    public List<SearchCriteria> getSearchCriteriaList() {        
        List<int> employees = employeeService.employeeList(); // NullPointerException 
        
        //code omitted for brevity
    }
}

【问题讨论】:

  • 你自己说的,你缺少正确的注释......
  • @Marek 抱歉,我已经使用了@Component,由于问题中的反引号,它不可见。现在显示出来了。有什么想法吗?
  • 我认为注释的顺序并不重要。不是吗?
  • @Marek 你能测试一下代码吗?
  • 只需按照 Akif Hadziabdic 的说明进行操作,您必须正确注释 EmployeeRequest 和 EmployeeService 类

标签: java spring spring-boot spring-mvc dependency-injection


【解决方案1】:

您缺少@Component 注释。

@Component
public class EmployeeRequest extends PageableCriteriaRequest {

   @Autowired
   public EmployeeService employeeService;
  ...
}

此外,请确保 EmployeeServiceIml 也使用 @Component@Service 注释进行注释。

@Service
public class EmployeeServiceIml implements EmployeeService {
  ...
}

另外,请确保您有 @SpringBootApplication 以及相同或子包中的所有组件。

@SpringBootApplication
public class SampleApplication {

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

【讨论】:

  • 感谢 Akif,但我已经使用了 @Component,由于问题中的反引号,它不可见。现在显示出来了。有什么想法吗?
  • 如果 EmployeeService 是一个接口,你在 EmployeeService 类或实现类上是否有组件或服务?可以分享一下代码吗?
  • EmployeeService 是一个接口,现在我正在尝试向该接口添加@Service 注释。我应该在服务的实现而不是接口中添加@Service注解吗?
  • 在实现中添加@Service注解,保证EmployeeService接口只有一个实现
  • @Component@Autowired 注释呢?我应该在哪里使用它们来解决这个问题?
【解决方案2】:

您需要将 @Service@Component 注释放在 EmployeeService 类的顶部,因为这是您要注入的类对象。

@Service
public class EmployeeService {
 // methods of EmployeeService
}

【讨论】:

  • 非常感谢。我也尝试过,但我认为我添加了不必要的课程。那么,您能否澄清一下我应该在以下类/服务中使用哪个注释?
  • 以下注释还是需要其他注释? @Service@Component@Autowired。 ==> 以下类:EmployeeRequestEmployeeService(这是接口)和EmployeeServiceImpl(这是服务类)。
猜你喜欢
  • 2018-07-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
相关资源
最近更新 更多