无法在 Spring 中注入服务

Cannot inject service in Spring

我是 Spring / Spring 的新手 引导并尝试向 class 注入服务。虽然我尝试了一些方法,例如@Autowired,服务实例始终为空并抛出“NullPointerException”错误。我不确定是否需要为 DI 注册此 class 和服务,但据我所知,在 class 中使用 @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
    }
}

您缺少 @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);
    }
}

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

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