import java.lang.reflect.Field;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringUtil() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
public static <T> T getBean(String name, Class<T> cls) throws BeansException {
return applicationContext.getBean(name, cls);
}
public static <T> T getBean(Class<T> cls) throws BeansException {
return applicationContext.getBean(cls);
}
public static void injectBean(Map<String, String> map) {
String className = (String)map.get("className");
if (className == null) {
throw new RuntimeException("map参数缺少className");
} else {
Class aClass;
try {
aClass = Class.forName(className);
if (aClass == null) {
throw new RuntimeException("className不存在");
}
} catch (ClassNotFoundException var10) {
throw new RuntimeException(var10);
}
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(aClass);
Field[] declaredFields = aClass.getDeclaredFields();
Field[] var5 = declaredFields;
int var6 = declaredFields.length;
for(int var7 = 0; var7 < var6; ++var7) {
Field declaredField = var5[var7];
String fieldName = declaredField.getName();
if (map.get(fieldName) != null) {
builder.addPropertyValue(fieldName, map.get(fieldName));
}
}
BeanDefinitionRegistry registry = (BeanDefinitionRegistry)applicationContext;
String id = (String)map.get("id");
if (id == null) {
registry.registerBeanDefinition(className, builder.getBeanDefinition());
} else {
registry.registerBeanDefinition(id, builder.getBeanDefinition());
}
}
}
}
使用
@Test
public void testAA() throws IOException {
ApprovalBillService service = SpringUtil.getBean(ApprovalBillService.class);
Boolean aBoolean = service.approvalBill(null);
System.out.println(aBoolean);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY