环境 1.Spring Boot 2.Mapper全部使用注解
//反射实体类com.test.Process
Class<?> clazz = Class.forName("com.test.Process");
// 调用任务
Method process = clazz.getMethod("tetsMethod", Integer.class, String.class);
Boolean next = (Boolean) process.invoke(clazz.newInstance(), 0,"str");
//被反射的类Process
@Component
public class Process implements HandleTask {
//此时 使用该方法获取不到testMapper 在执行过程中会出现空指针异常
@Autowired
TestMapper testMapper;
public boolean testMethod(int i,String str){
testMapper.query(i,str);
}
}
/**
* @author LEI
* Created by LEI on 2019/9/25.
*/
public class SpringBootCtx {
private static ConfigurableApplicationContext applicationContext;
public static void setApplicationContext(ConfigurableApplicationContext applicationContext) {
SpringBootCtx.applicationContext = applicationContext;
}
public static ConfigurableApplicationContext getApplicationContext() {
return applicationContext;
}
public static ConfigurableListableBeanFactory getBeanFactory(){
return applicationContext.getBeanFactory();
}
}
2. 在spirng boot启动时保存上下文
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext =SpringApplication.run(CloudhomeApplication.class, args);
SpringBootCtx.setApplicationContext(applicationContext);
}
3. 在使用时
//被反射的类Process
@Component
public class Process implements HandleTask {
//此时 使用该方法获取不到testMapper 在执行过程中会出现空指针异常
//@Autowired
//TestMapper testMapper;
public boolean testMethod(int i,String str){
TestMapper testMapper = SpringBootCtx.getBeanFactory().getBean(TestMapper.class);
testMapper.query(i,str);
}
}