V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Weixiao0725
V2EX  ›  Java

Spring 动态增加新的 Bean 到容器中?

  •  
  •   Weixiao0725 · Sep 19, 2016 · 6263 views
    This topic created in 3514 days ago, the information mentioned may be changed or developed.

    Spring 如何实现动态的增加一个 Bean 到容器中呢?注意:不是在 spring 启动的时候,所以利用 spring 的事件机制貌似不可以啊。

    Supplement 1  ·  Sep 20, 2016

    many thanks for your answers! 大致的步骤为:

    
                    ApplicationContext applicationContext = 
    				new ClassPathXmlApplicationContext("applicationContext.xml");
    		
    		//将applicationContext转换为ConfigurableApplicationContext
    		ConfigurableApplicationContext configurableApplicationContext = 
    				(ConfigurableApplicationContext) applicationContext;
    		
    		
    		// 获取bean工厂并转换为DefaultListableBeanFactory
    		DefaultListableBeanFactory defaultListableBeanFactory = 
    				(DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
    		
    		// 通过BeanDefinitionBuilder创建bean定义
    		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
    				.genericBeanDefinition(YOUR_CLASS.class);
    		
    		// 设置属性userAcctDAO,此属性引用已经定义的bean:userAcctDAO
    		beanDefinitionBuilder
    				.addPropertyReference("name", "weixiao");
    		beanDefinitionBuilder
    				.addPropertyReference("passwd", "897932384");
    		
    		
    		// 注册bean
    		defaultListableBeanFactory.registerBeanDefinition("bean-id",
    				beanDefinitionBuilder.getRawBeanDefinition());
    
    
    6 replies    2016-09-20 21:25:34 +08:00
    darkfireworld
        1
    darkfireworld  
       Sep 19, 2016 via Android
    可以考虑工厂类
    q397064399
        2
    q397064399  
       Sep 19, 2016
    如何动态使用 bean 呢?怎么注解?
    fqs
        3
    fqs  
       Sep 20, 2016 via Android
    直接获取上下文做 bean 注入,应该是可以的。
    ppwangs
        4
    ppwangs  
       Sep 20, 2016
    这店就是 guice 优于 spring 的地方了
    Infernalzero
        5
    Infernalzero  
       Sep 20, 2016
    实现 BeanDefinitionRegistryPostProcessor 即可或者从 applicationContext 获取 beanFactory 直接注册
    Ouyangan
        6
    Ouyangan  
       Sep 20, 2016
    @Infernalzero 同意这种方式 ,粗暴点直接获取 context
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2699 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 02:15 · PVG 10:15 · LAX 19:15 · JFK 22:15
    ♥ Do have faith in what you're doing.