在JavaSpring框架中从字符串调用存储库
有没有从字符串调用接口的方法在JavaSpring框架中从字符串调用存储库,java,spring,reflection,spring-data,Java,Spring,Reflection,Spring Data,有没有从字符串调用接口的方法 String repName = "package." + modelName + "Repository"; Class<?> repo = Class.forName(repName); Object obj = repo.getDeclaredConstructor().newInstance(); Method setNameMethod = obj.getClass().getMethod("findById", int.class); s
String repName = "package." + modelName + "Repository";
Class<?> repo = Class.forName(repName);
Object obj = repo.getDeclaredConstructor().newInstance();
Method setNameMethod = obj.getClass().getMethod("findById", int.class);
setNameMethod.invoke(obj, 7); // passing 7
String repName=“package.”+modelName+“Repository”;
Class repo=Class.forName(repName);
Object obj=repo.getDeclaredConstructor().newInstance();
方法setNameMethod=obj.getClass().getMethod(“findById”,int.class);
setNameMethod.invoke(obj,7);//通过7
这应该适用于普通的方法/类,但如何动态调用接口?如果您在spring上下文中操作,则可以使用
ApplicationContext
-bean:
@Component
class Test {
private final ApplicationContext context;
@Autowired
public Test(ApplicationContext context) {
this.context = context;
}
public void callRepository(String repName) /* here should come some throws declarations */ {
Class<?> type = Class.forName(repName);
Object instance = context.getBean(repName);
type.getMethod("findById", int.class).invoke(instance, 7);
}
}
@组件
课堂测试{
私有最终应用程序上下文上下文;
@自动连线
公共测试(ApplicationContext上下文){
this.context=上下文;
}
public void callRepository(String repName)/*这里应该有一些抛出声明*/{
Class type=Class.forName(repName);
对象实例=context.getBean(repName);
getMethod(“findById”,int.class).invoke(实例,7);
}
}
ApplicationContext
允许您访问每个注册的bean。如果您在spring上下文中操作,则可以使用ApplicationContext
-bean:
@Component
class Test {
private final ApplicationContext context;
@Autowired
public Test(ApplicationContext context) {
this.context = context;
}
public void callRepository(String repName) /* here should come some throws declarations */ {
Class<?> type = Class.forName(repName);
Object instance = context.getBean(repName);
type.getMethod("findById", int.class).invoke(instance, 7);
}
}
@组件
课堂测试{
私有最终应用程序上下文上下文;
@自动连线
公共测试(ApplicationContext上下文){
this.context=上下文;
}
public void callRepository(String repName)/*这里应该有一些抛出声明*/{
Class type=Class.forName(repName);
对象实例=context.getBean(repName);
getMethod(“findById”,int.class).invoke(实例,7);
}
}
ApplicationContext
允许您访问每个注册的bean