use*_*969 1 java reflection spring web-applications
实际上,我要调用的是一种服务方法,所以有人说,使用常规反射,如何加载自动装配的元素?我是Spring框架的新手。我正在研究使用Spring-hibernate框架设计的Web应用程序。所以在一种情况下,我将类名和方法名保存在DB中。现在我想通过反射调用方法:
Class cls = Class.forName("com.xyz.pqr.Invest");
Object obj = cls.newInstance();
//call the printIt method
Method method = cls.getDeclaredMethod("exec", noparams);
method.invoke(obj, null);
Run Code Online (Sandbox Code Playgroud)
通过从数据库获取类名和方法名。但这没有实现我的目的。请告诉我们如何使用spring通过反射调用方法。我用谷歌搜索了一下,发现实现了ApplicationContextAware。但不清楚。实际上,我要调用的是一种服务方法,所以有人说,使用常规反射,如何加载自动装配的元素?Invest是服务类,因为我们有api exec来处理一些数据
public void exex(int a, int b, String c){**}
Run Code Online (Sandbox Code Playgroud)
谢谢
您需要做的是让您的调用者ApplicationContextAware使用getBean()方法来Invest代替而不是获取类的实例cls.newInstance()。
像下面这样:
public TheCaller implements org.springframework.context.ApplicationContextAware {
/** The spring application context */
@Autowired
private org.springframework.context.ApplicationContext springContext;
public void callService(String serviceName, String theClass, String methodName) {
Class cls = Class.forName(theClass);
Object obj = applicationContext.getBean(serviceName); // Or use applicationContext.getBeansOfType(cls)
Method method = cls.getDeclaredMethod(methodName, noparams);
method.invoke(obj, null);
}
}
Run Code Online (Sandbox Code Playgroud)
该服务名是在春天配置的bean的名字。
| 归档时间: |
|
| 查看次数: |
1634 次 |
| 最近记录: |