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

Posted

技术标签:

【中文标题】如何为同一服务使用@Autowired 注解两个或多个不同的组件类?【英文标题】:How to use @Autowired annotation two or more different Component class for same service? 【发布时间】: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 创建实例。 【参考方案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 创建的。我创建了一个组件并尝试调用服务。 @亚历克斯

以上是关于如何为同一服务使用@Autowired 注解两个或多个不同的组件类?的主要内容,如果未能解决你的问题,请参考以下文章

@Autowired注解与@Qualifier注解搭配使用

注解 @Resource与@Autowired与@Component的使用

Solr Highlighting:如何为同一字段请求多个片段长度?

@Autowired注解与@Qualifier注解搭配使用----解决多实现选择注入问题

Spring服务定制

如何为sensio框架控制器监听器启用注解阅读器服务?