目录
获取BeanFactory
扩展接口BeanFactoryPostProcessor或者该接口的子接口,并注入Spring即可获取BeanFactory。
@Component
public class DefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) throws BeansException {
// 测试注入HelloWord
HelloWord beanClass = new HelloWord();
beanFactory.registerSingleton("hello1", beanClass);
// 缓存beanFactory引用
ConfigurableListableBeanFactoryUtil.setContext(beanFactory);
}
public void postProcessBeanDefinitionRegistry(
BeanDefinitionRegistry registry) throws BeansException {
}
}
保存注册
注册:beanFactory.registerSingleton(beanName,singletonObject);
保存:使用静态属性缓存
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
/**
* 用来缓存BeanFactory 以及 获取和注册bean
*/
public class BeanFactoryUtil {
private static ConfigurableListableBeanFactory beanFactory;
/**
* 报错beanFactory对象
* @param beanFactory1
*/
public static void setContext(ConfigurableListableBeanFactory beanFactory1) {
beanFactory = beanFactory1;
}
/**
* 注册单例
* @param beanName
* @param singletonObject
*/
public static void registerSingleton(String beanName, Object singletonObject) {
beanFactory.registerSingleton(beanName,singletonObject);
}
/**
* 根据Bean名称获取Bean对象
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return beanFactory.getBean(beanName);
}
/**
* 根据类型获取Bean对象
* @param t
* @return
*/
public static <T> T getBean(Class<T> t) {
return beanFactory.getBean(t);
}
}
测试验证
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.spring4condition.register.BeanFactoryUtil;
import com.example.spring4condition.register.HelloWord;
@SpringBootTest(classes = Spring4ConditionApplication.class)
@RunWith(SpringRunner.class)
public class TestReristeBean {
@Autowired(required = false)
@Qualifier("hello1")
private HelloWord hello1;
@Test
public void test3(){
System.out.println("hello1:"+this.hello1);
HelloWord beanClass = new HelloWord();
BeanFactoryUtil.registerSingleton("hello2", beanClass);
HelloWord hello2 = (HelloWord) BeanFactoryUtil.getBean("hello2");
System.out.println("hello2:" + hello2.say());
}
}
end ...