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