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

1.编写service接口与实现类

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

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

//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层方法

 

转载于:https://my.oschina.net/u/2251646/blog/3092797

你可能感兴趣的:(java class反射之使用springAutowired注入service方法调用)