spring+mybatis接口Dao的反射调用
默认项目已经配置好了springMVC和mybatis
一、步骤
1 利用spring注入接口(对象)
@Autowired
private CustomerInfoDao customerInfoDao;
2 通过注入的接口获取类Class
Class c=customerInfoDao.getClass();
3 通过方法名获取接口中的方法
Method method = c.getMethod("selectValidPolicyInfo", CustomerInfo.class);
4反射调用接口方法
Object obj=method.invoke(customerInfoDao, customerInfo);
成了
二、完全体
这里用了一个springboot的测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes={ProviderCenterApplication.class})
public class TestInvoke {
@Autowired
private CustomerInfoDao customerInfoDao;
@Test
public void test1() {
try {
//先配置一个方法的参数
CustomerInfo customerInfo = new CustomerInfo();
customerInfo.setCustomerno("P00000000916769");
//获取类
Class c=customerInfoDao.getClass();
//通过方法名获取方法
Method method = c.getMethod("selectValidPolicyInfo", CustomerInfo.class);
//反射调用
Object obj=method.invoke(customerInfoDao, customerInfo);
//以下是输出的验证数据
List<CustomerPolicyInfo> list = (List<CustomerPolicyInfo>) obj;
for (CustomerPolicyInfo p:list) {
System.out.println(p.getPolicyno());
}
System.out.println("结束");
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是调用接口中的那个方法
public interface CustomerInfoDao {
List<CustomerPolicyInfo> selectValidPolicyInfo(CustomerInfo customerInfo);
}