java class反射之使用springAutowired注入service方法调用

1.编写service接口与实现类java

2.经过class反射获取到其service实现类路径下的实体类web

3.主要代码块,关于WebApplicationContext相关介绍可上网获知spring

//WebApplicationContext中能够得到ServletContext的引用,以便web应用能够访问spring上下文,spring中提供WebApplicationContextUtils的getWebApplicationContext(ServletContext src)方法来得到WebApplicationContext对象

WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
//反射获取到对应java
Class c1 = Class.forName(packageName);
//获取方法名称,methodName为service层方法
Method method = c1.getDeclaredMethod(methodName,String.class);
//获取注入的service类型,serviceName值为:xxServceiImpl,
//在经过invoke方法执行对应的方法
method.invoke(wac.getBean(serviceName),params);

4.还能够经过重写注解方法,实现spring DI注入service或dao,实现java反射调用service层或dao层方法对象

相关文章
相关标签/搜索