新建ApplicationContextGetBeanHelper类作为单独获取bean的类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextGetBeanHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static Object getBean(String className) throws BeansException,IllegalArgumentException {
if(className==null || className.length()<=0) {
throw new IllegalArgumentException("className为空");
}
String beanName = null;
if(className.length() > 1) {
beanName = className.substring(0, 1).toLowerCase() + className.substring(1);
} else {
beanName = className.toLowerCase();
}
return applicationContext != null ? applicationContext.getBean(beanName) : null;
}
}
在需要使用反射的地方,调用相关实例
import com.ttckj.common.utils.ApplicationContextGetBeanHelper;
import com.ttckj.common.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Method;
@Service
@Slf4j
public class TestServiceImpl {
public void updateAfterDoSomething(String tableName,Long userId) {
try {
String className = CommonUtil.underLineToTuofeng(tableName)+"ServiceImpl";
Object object = ApplicationContextGetBeanHelper.getBean(className);
Class clazz = object.getClass();
Method bean = clazz.getMethod("queryInfo",Long.class);
bean.invoke(object, userId);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Service
@Slf4j
public class MyServiceImpl {
@Resource
private TestServiceImpl handlerService;
public void businessDo(Long userId) {
handlerService.updateAfterDoSomething("sys_user_info",userId);
}
}
这时候就需要有SysUserInfoServiceImpl类来执行反射里面的queryInfo方法
import org.springframework.stereotype.Service;
@Service
public class SysUserInfoServiceImpl {
public void queryInfo(Long userId){
System.out.println("userId = " + userId);
}
}
附上反射里面的CommonUtil.underLineToTuofeng(tableName)方法
import cn.hutool.core.util.StrUtil;
public class CommonUtil {
public static String underLineToTuofeng(String str) {
return org.apache.commons.lang3.StringUtils.capitalize(StrUtil.toCamelCase(str));
}
}