反射加载类无法注入变量解决方法

在Java中定义一个类,类中注入了一个service,代码如下:

@Component
public class AffairIdHandler implements PropertyHandler {

    @Autowired
    private AffairService affairService;

    @Override
    public JSONObject handle(JSONObject auditData, String handleKey) {
        Long affairId = auditData.getLong(handleKey);
        JSONObject affair = new JSONObject();
        //......
        return affair;
    } 
}

但是由于AffairIdHandler需要通过反射动态地加载,使用它的类不是通过注入的方式获取实例的,导致AffairService无法由spring自动注入,因为AffairIdHandler已经脱离spring的管理,所以affairService变量为null,具体的解决办法如下:

@Service
public class OperationService {

    @Autowired
    private ApplicationContext context;

    public List<JSONObject> handleProperties(KeyMapper.Operation operation, JSONObject auditData) {
        List<JSONObject> form = new ArrayList<>();
        Map<String, KeyMapper.Operation.Property> properties = operation.getProperties();
        for (Map.Entry<String, KeyMapper.Operation.Property> entry : properties.entrySet()) {
            //......
            if (handlerUrl == null) {
                component.put("value", auditData.get(key));
            } else {
                try {
                    Class<?> handler =  Class.forName(handlerUrl);
                    PropertyHandler propertyHandler = (PropertyHandler)context.getAutowireCapableBeanFactory()
                                        .createBean(handler, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
            form.add(component);
        }
        return form;
    }

}

 

即使用ApplicationContext获取AutowireCapableBeanFactory示例,并通过AutowireCapableBeanFactory的实例的createBean()方法来创建bean,那么AffairIdHandler类中使用@Autowired注入的变量就可以自动注入。


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值