【问题标题】:How to use @Autowired annotation two or more different Component class for same service?如何为同一服务使用@Autowired 注解两个或多个不同的组件类?
【发布时间】:2020-09-18 04:46:31
【问题描述】:

例如,有一个如下所示的类。 第一个XService serviceA 类中不为空,但第二个XService serviceAmountValidator 中为空。我得到NullPointerException 我尝试创建bean new 它工作,然后我在调用AmountValidateService outsideRestService 时得到同样的异常在XService。 如何在使用 @Autowired 注释的任何地方使用 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
          }
        }

AmountValidator 添加到类 Validator 的规则中。

@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
  }
}

【问题讨论】:

  • 您能分享一下 AmountValidateService 的类定义吗?另外请整理一下代码和问题,一开始有点难以掌握
  • AmountValidateService 具有 @service 注释的经典服务类。对不起复杂的问题。我清理了这个问题以便更容易理解。
  • 您是使用 new 关键字自己创建 AmountValidator 的实例还是创建 BY 上下文? @Autowired 仅适用于上下文创建的实例,因为注入是由 spring 上下文产生的。
  • 我看到您已经编辑了代码,但仍然注意到 class AmountValidator() ... 是括号中的意思吗?
  • 我知道有些部分会使代码有点复杂,但是我使用了策略模式,我不知道如何解释。 AmountValidator 类已添加到 Starategy 类的规则中。请参阅:Validataor 类规则。而且我从来没有为 AmountValidator 创建实例。

标签: spring-boot autowired


【解决方案1】:

所有用@Component@Service注解的类都被认为是特殊的类,它们被Spring通过DI自动实例化,用new实例化它们就违背了DI的目的。

这些特殊类被命名为Spring Beans

每次应用启动时,框架实例全部Spring Beans,所有@Autowired字段都由Spring自动注入。但是Spring Beans 必须在类路径中的某处定义。否则您将收到NoSuchBeanDefinitionException

作为回答这个问题的尝试,因为我没有堆栈跟踪,也没有所有 Spring Bean 定义:

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

您可以自己设置字段,但正如我之前提到的,它违背了DI 的目的

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • “您自己创建组件”是什么意思?组件无论如何都不是由 Spring 创建的。我创建了一个组件并尝试调用服务。 @亚历克斯
    猜你喜欢
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多