Spring @Autowired带注释的对象值为null

时间:2013-07-31 00:25:18

标签: spring annotations autowired

//我的工厂类

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

//我的Validator类

@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());
        }
    }

我的包扫描级别更高。发生的事情是我的virginAmericaValidator总是空的。为什么@Autowired注释不起作用。

1 个答案:

答案 0 :(得分:5)

您当前的方法不适用于Spring,因为您最终使用new UserRewardAccountValidatorFactory来创建实际上完全绕过Spring上下文的实例。应该可行的两种方法是:

一个。使用factory-method并使用xml定义bean:

<bean class="package.UserRewardAccountValidatorFactory" name="myfactory" factory-method="getInstance"/> 

这实际上将返回您作为Spring bean创建的实例,并且应该干净地自动装配。

湾使用基于Java @Configuration的机制:

@Configuration
public class MyBeanConfiguration {
   @Bean 
   public UserRewardAccountValidatorFactory myFactory() {
       return UserRewardAccountValidatorFactory.getInstance();
   }
}