【发布时间】:2020-09-18 04:46:31
【问题描述】:
例如,有一个如下所示的类。
第一个XService service 在A 类中不为空,但第二个XService service 在AmountValidator 中为空。我得到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