JAva反射spring注入@Autowired

964 ワード

昨日ある機能を書いて反射したので、書き終わったら、運転エラー:XXXXXService is nullよく見ると、nullのXXXXXServiceは自動注入で、Springデフォルトで発生したbeanは一例です...
前の反射コード
XService xService = new XService();
Class c = xService.getClass();
Method m = c.getDeclaredMethod(methodName);
return m.invoke(xService);

XServiceにはこのようなコードがあります
@Autowired
private XXXXService xxxxService;

XServiceのmethodNameメソッドでxxxxサービスのメソッドが呼び出され、エラーが発生しました
反射コードをに変更
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
Class cls = wac.getBean("XService").getClass();
Method m = cls.getDeclaredMethod(methodName);
return m.invoke(wac.getBean("XService"));

これでいいのですが^^;