BeanFactory动态注入到Interface
写点笔记
共 3673字,需浏览 8分钟
·
2022-04-10 20:02
1、首先定义承载对象的接口;
public interface Bean {
}
2、定义BeanFactory,实现getObject方法。
public class MyBeanFactoryimplements FactoryBean{
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public static final Mapmap=new HashMap<>();
public T getObject() throws Exception {
if (CollectionUtils.isEmpty(map)||!map.containsKey("lele")){
synchronized (map){
return (T) execute();
}
}else{
return (T) map.get("lele");
}
}
private Object execute() {
Mybean mybean = new Mybean(name,age);
map.put("lele",mybean);
return mybean;
}
public Class getObjectType() {
return null;
}
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}
3、将BeanFactory注入到ioc容器。
public class MyBeanFactoryBean extends MyBeanFactory{
}
Spring注入bean装配厂工具类
public class MySpringContentUtils {
public static ConfigurableApplicationContext context;
public static ConfigurableApplicationContext getContext() {
return context;
}
public static void setContext(ConfigurableApplicationContext context) {
MySpringContentUtils.context = context;
}
public static void registerBean(String name, Class factoryClazz, Class beanClazz, MutablePropertyValues mpv) throws BeanDefinitionStoreException {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz);
GenericBeanDefinition beanDefinition = (GenericBeanDefinition)beanDefinitionBuilder.getRawBeanDefinition();
beanDefinition.setBeanClass(factoryClazz == null ? beanClazz : factoryClazz);
beanDefinition.setPropertyValues(mpv);
BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry)context.getBeanFactory();
beanFactory.registerBeanDefinition(name, beanDefinition);
}
public staticT getBean(String name) throws BeansException {
return (T) context.getBean(name);
}
}
将MyBeanFactory注入到beanDefianition中
public class MyConfig implements BeanDefinitionRegistryPostProcessor {
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
MutablePropertyValues mv=new MutablePropertyValues();
mv.add("name","jasldf");
mv.add("age","123");
MySpringContentUtils.registerBean("jk",MyBeanFactoryBean.class,Mybean.class,mv);
}
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
}
public class MyTianApplicationInitlize implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
MySpringContentUtils.setContext(configurableApplicationContext);
}
}
至此,我们需要的功能就已经写完了。这里我们测试一下。
测试如下;
评论