欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring中自定义对象交给spring容器管理的4种方式

程序员文章站 2022-06-17 08:18:40
1、自定义一个 BeanDefinition@Componentpublic class BeanPro implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, Ordered { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {...

1、自定义一个 BeanDefinition

@Component
public class BeanPro implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, Ordered {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        //查询BeanDefinition
        final String[] beanDefinitionNames = registry.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            BeanDefinition beanDefinition = registry.getBeanDefinition(beanDefinitionName);
            System.out.println(beanDefinition);
        }

        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        genericBeanDefinition.setBeanClass(BeanDefinitionBean.class);
        MutablePropertyValues propertyValues = genericBeanDefinition.getPropertyValues();
        propertyValues.add("name","Jack");
        registry.registerBeanDefinition("beanDefinitionBean",genericBeanDefinition);


    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        String[] beanDefinitionNames = registry.getBeanDefinitionNames();

        DefaultListableBeanFactory beanFactory1 = (DefaultListableBeanFactory)beanFactory;
        beanFactory1.setAllowBeanDefinitionOverriding(true);
        beanFactory1.setAllowCircularReferences(true);
        beanFactory1.setAllowRawInjectionDespiteWrapping(true);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

2、手动创建了对象,并且交给spring管理了

applicationContext.getBeanFactory().registerSingleton("jack", new Jack());

3、实现 FactoryBean接口

/** 
 *
 * 灵活定义需要我们自己创建的实例的时候,我们可以实现factoryBean接口
 * 在getObject方法里面定义实例化过程
 *
 */
@Component
public class FactoryBeanDemo implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return new Student();
    }

    @Override
    public Class<?> getObjectType() {
        return Student.class;
    }
}

4、@Bean注解

本文地址:https://blog.csdn.net/qq_31391225/article/details/112230203