Spring boot 如何为同一服务使用@Autowired注释两个或多个不同的组件类?

Spring boot 如何为同一服务使用@Autowired注释两个或多个不同的组件类?,spring-boot,autowired,Spring Boot,Autowired,例如,创建一个如下所示的类。 类A中的第一个XService服务不为null,但AmountValidator中的第二个XService服务为null。我得到了NullPointerException,我尝试创建一个新的bean,它可以正常工作,然后在XService中调用AmountValidateService OuternestService时得到了相同的异常。 我如何在使用@Autowired annotation的任何地方使用XService 我的主要班级: @Service cla

例如,创建一个如下所示的类。 类A中的第一个XService服务不为null,但AmountValidator中的第二个XService服务为null。我得到了NullPointerException,我尝试创建一个新的bean,它可以正常工作,然后在XService中调用AmountValidateService OuternestService时得到了相同的异常。 我如何在使用@Autowired annotation的任何地方使用XService

我的主要班级:

@Service
 class A extends AbstractA implements  IA {    
 @Autowired
 XService service; //first autowired definition. code go to check() method. service not null now.

public doSometing(){
    validator.check();
    service.methodA();
    super.AbstractMethod();
  }
}
类A中使用的验证程序类:

 class Validator<T> implements IValidator<T> {
         public void check(){
             rule.check(); // rule have a implements IValidator eg: amountValidator, dateValidator class
          }
        }

您有一个错误,因为您试图自己创建组件/bean/服务。正如我在评论中提到的,当你自己创建组件时,@Autowired不起作用-那就是你有NPE

所有用@Component注释的类,@Service都被认为是特殊的类,由Spring通过自动实例化,用新的方法实例化它们,这违背了

这些特殊类被命名为

每次应用程序启动时,Spring都会自动注入框架实例中的所有Springbean和所有@Autowired字段。但是Springbean必须在类路径的某个地方定义。否则,您将收到NoSuchBeanDefinitionException

为了回答这个问题,因为我没有堆栈跟踪,也没有所有SpringBean定义:

当您使用新的XService实例化XService时,您的新实例将不会实际初始化字段AmountValidateService OutlineRestService,实际上将其保留为null

你可以自己设置场地,但正如我前面提到的,它违背了


您的问题并不复杂,它是不完整的。

您能分享AmountValidateService的类定义吗?另外,请整理一下代码和问题,在firstAmountValidateService中有@service注释的经典服务类有点难理解。对不起,这个问题很复杂。为了更容易理解,我清理了这个问题。您是使用新关键字自己创建AmountValidator的实例,还是通过上下文创建@Autowired仅适用于上下文创建的实例,因为注入是由spring上下文生成的。我看到您已经编辑了代码,但仍然注意到这个类AmountValidator。。。括号是有意的吗?我知道有些部分使代码有点复杂,但我使用了一种策略模式,我不知道如何解释它。AmountValidator类已添加到Starategy类中的规则中。请参阅:Validataor类规则。我从来没有为AmountValidator创建intance。什么叫“您自己创建组件”?组件并不是由Spring创建的。我创建一个组件并尝试调用服务@亚历克斯
@Component
class AmountValidator implements IValidator<T>{
@Autowired
XService service; // code comes here service is null. same service class mentioned above class A.

@Override
public void check(){
     service.validateAmount(); // nullPointerException.
  }
}
@Component
class XService {
@Autowired 
AmountValidateService outsideRestService;

public validateAmount(){
    outsideRestService.validate(); // nullPointer when create XService with the `New` keyword
  }
}