Java通过反射加载的类中的变量无法注入的解决办法

在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注入的变量就可以自动注入。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容