com.mooez.event.commons.utils.BeanUtils Maven / Gradle / Ivy
package com.mooez.event.commons.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.function.Supplier;
/**
* Description:
* Author: Mooez
* Date: 2022/9/23 19:51
*/
public class BeanUtils implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
/**
* 提供静态Bean属性对象的引用
*/
private static BeanDefinitionRegistry beanDefinitionRegistry;
/**
* 提供静态IOC容器中Bean的获取
*/
private static ApplicationContext applicationContext;
/**
* 通过反射获取IOC的bean对象
*
* @param beanClass
* @param
* @return
*/
public static T getBean(Class beanClass) {
return applicationContext.getBean(beanClass);
}
/**
* 手动注册对象
* @param beanName
* @param bean
*/
public static void registerBean(String beanName, Object bean) {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(bean.getClass(), new Supplier() {
@Override
public Object get() {
return bean;
}
});
//注册bean对象
beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
}
/**
* 将beanDefinitionRegistry设置成静态属性直接调用
*
* @param registry the bean definition registry used by the application context
* @throws BeansException
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
BeanUtils.beanDefinitionRegistry = registry;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
/**
* 将applicationContext设置成静态属性直接调用
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanUtils.applicationContext = applicationContext;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy