Spring@Autowired注释对象值为null
//我的工厂班Spring@Autowired注释对象值为null,spring,annotations,autowired,Spring,Annotations,Autowired,//我的工厂班 @Component public class UserRewardAccountValidatorFactory { @Autowired private VirginAmericaValidator virginAmericaValidator; private static class SingletonHolder { static UserRewardAccountValidatorFactory instance = new
@Component
public class UserRewardAccountValidatorFactory {
@Autowired
private VirginAmericaValidator virginAmericaValidator;
private static class SingletonHolder {
static UserRewardAccountValidatorFactory instance = new UserRewardAccountValidatorFactory();
}
public static UserRewardAccountValidatorFactory getInstance() {
return SingletonHolder.instance;
}
private UserRewardAccountValidatorFactory() {}
public PartnerValidator getPartnerValidator(Partner partner){
return virginAmericaValidator;
}
}
//我的验证器类
@Service
public class VirginAmericaValidator implements PartnerValidator {
@Override
public void validate(String code) throws InvalidCodeException{
//do some processing if processing fails throw exception
if (code.equals("bad".toString())){
throw new InvalidCodeException();
}
}
}
//用法:
PartnerValidator pv = UserRewardAccountValidatorFactory.getInstance().getPartnerValidator(partner);
if (pv != null){
try {
pv.validate(userRewardAccount);
} catch (InvalidCodeException e){
return buildResponse(ResponseStatus.INVALID_USER_REWARD_ACCOUNT, e.getMessage());
}
}
我的包扫描级别要高得多。发生的是我的维吉尼亚美国骑士队总是空的。为什么@Autowired annotation不起作用。您当前的方法将无法与Spring一起使用,因为您最终将使用
新的UserRewardAccountValidatorFactory
来创建实际上完全绕过Spring上下文的实例。以下是两种可能有效的方法:
a。使用工厂方法
并使用xml定义bean:
<bean class="package.UserRewardAccountValidatorFactory" name="myfactory" factory-method="getInstance"/>
您当前的方法不适用于Spring,因为您最终将使用
new UserRewardAccountValidatorFactory
来创建实际上完全绕过Spring上下文的实例。以下是两种可能有效的方法:
a。使用工厂方法
并使用xml定义bean:
<bean class="package.UserRewardAccountValidatorFactory" name="myfactory" factory-method="getInstance"/>
或者c)使用@Configurable和AspectJ,然后Spring甚至在由
new
创建的实例中进行注入(我提到这一点仅仅是为了完成,因为为了对抗关于Spring不能注入由new
生成的类的谣言,因为它是错误的)如果我让VirginaAmericavalidator从另一个抽象类扩展并在那里实现接口,这会让spring autowire为我服务吗?不,这也不会起作用,因为问题仍然在创建UserRewardAccountValidatorFactory
的过程中,而不是在验证程序中。您应该能够使用我提到的两个选项之一来实现它。Ralph提到的方法也很好,但它需要完整的AspectJ编织来让它工作。或者c)使用@Configurable和AspectJ,然后Spring注入,即使是在new
(我提到这一点仅仅是为了防止这种谣言,即Spring不能注入由new
生成的类,因为它是错误的)如果我让VirginaAmericavalidator从另一个抽象类扩展并在那里实现接口,这会让spring autowire为我服务吗?不,这也不会起作用,因为问题仍然在创建UserRewardAccountValidatorFactory
的过程中,而不是在验证器中。您应该能够让它使用以下两个选项之一工作:我已经提到了。拉尔夫提到的方法也是很好的,但它需要完整的AspectJ编织才能工作。