手动注入bean
程序员文章站
2022-06-04 10:45:39
...
一、工具类
public class SpringCtxUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
private static DefaultListableBeanFactory defaultListableBeanFactory;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
AnycloudApplication.applicationContext = applicationContext;
defaultListableBeanFactory = (DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
}
public static <T> T getBean(Class<T> clazz) {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
String className = clazz.getName();
defaultListableBeanFactory.registerBeanDefinition(className, beanDefinitionBuilder.getBeanDefinition());
return (T) applicationContext.getBean(className);
}
public static void destroy(String className){
defaultListableBeanFactory.removeBeanDefinition(className);
System.out.println("destroy " + className);
}
}
二、使用工具类注入类
UserService userService= SpringCtxUtil.getBean(UserService.class);
三、注意
在我们需要调用的类前加上注解@Primary
@Primary
public Class UserService {
}
如果我们在需要注入的类中使用了@Transactional注解,一般会导致注入失败,请参考下面的博文
https://blog.csdn.net/weixin_36524613/article/details/85258442