在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需要通過反射動態(tài)地加載哑子,使用它的類不是通過注入的方式獲取實例的饶套,導致AffairService無法由spring自動注入芒填,因為AffairIdHandler已經(jīng)脫離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()方法來創(chuàng)建bean剧罩,那么AffairIdHandler類中使用@Autowired注入的變量就可以自動注入斑响。