在春季运行时注册bean(prototype)

只需要社区评估的东西。下面是一段代码,它是一个创建特定类型实例的简单工厂。该方法将在上下文中将 Bean 注册为原型并返回实例。这是我第一次在运行时配置 Bean。您能评估并提供反馈吗?提前感谢您。

package au.com.flexcontacts.flexoperations;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;

import au.com.flexcontacts.exceptions.SyncClassCreactionError;

/**
 * @author khushroo.mistry
 * Class purpose: Simple Factory to create an 
 * instance of SynchroniseContactsService and register it in the Spring IoC.
 */
public final class FLEXSyncFactory implements ApplicationContextAware {

    private static AbstractApplicationContext context;


    /**
     * @param username
     * @param password
     * @param syncType
     * @return the correct service class
     * @throws SyncClassCreactionError
     * The method registers the classes dynamically into the Spring IoC
     */
    public final SynchroniseContactsService createSyncService(String username, String password, SyncType syncType) throws SyncClassCreactionError {

        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();

        try {

            //Register the bean in the IoC
            BeanDefinition bdb = new GenericBeanDefinition();
            bdb.setBeanClassName(syncType.getClassName());
            bdb.setScope("prototype");
            ConstructorArgumentValues constructor = bdb.getConstructorArgumentValues();
            constructor.addIndexedArgumentValue(0, username);
            constructor.addIndexedArgumentValue(1, password);
            beanFactory.registerBeanDefinition(syncType.getInstanceName(), bdb);

            //Return instance of bean
            return (SynchroniseContactsService) beanFactory.getBean(syncType.getInstanceName());
        } catch (Exception e) {
            e.printStackTrace();
            throw new SyncClassCreactionError("Error: Illegal Handler");
        }

    }

    public void setApplicationContext(ApplicationContext applicationContext)
    throws BeansException {
        context = (AbstractApplicationContext) applicationContext;

    }

}

FLEX 同步工厂已在 IoC 容器中配置为单一实例。因此,要创建新的同步管理器,请执行以下操作:

flexSyncFactory.createSyncService(userName, password, SyncType.FULL);

我正在使用Spring 3.1。请查看并提供您的宝贵反馈。

亲切问候。


答案 1

这纯粹是我的观点,而不是专家的观点:

Spring提供了两种用于自定义修改应用程序上下文的机制 - 使用BeanFactoryPostProcessor,允许修改现有的Bean定义或添加新的Bean定义,以及BeanPostProcessors,允许修改Bean实例(将它们包装在代理等周围)。

Spring 没有提供任何其他本机方法来在运行时动态添加 Bean 定义或 Bean 实例,但就像您通过获取底层 Bean 工厂实例并添加 Bean 定义一样,这是一种方法。它有效,但存在风险:

  • 如果用新类型覆盖现有 Bean 名称会发生什么情况,如何处理已注入此 Bean 的位置。另外,如果现有的Bean名称被完全不同的类型覆盖,会发生什么情况!

  • 这个新注册的bean不会自动连接任何字段,也不会被注入到其他bean中 - 所以本质上bean工厂纯粹充当保存bean的注册表,而不是真正的依赖注入功能!

  • 如果在应用程序上下文中调用了 a,则支持 Bean 工厂将被覆盖并创建一个新 Bean 工厂,因此直接针对 Bean 工厂注册的任何 Bean 实例都将丢失。refresh()

如果目标纯粹是创造由Spring自动布线的豆子,我会选择像@Configurable这样的东西。如果上述风险是可以接受的,那么您的方法也应该有效。


答案 2

这对我有用:http://random-thoughts-vortex.blogspot.com/2009/03/create-dynamically-spring-beans.html

声明一个专用的Spring上下文bean,它将实现ApplianceContextAware和BeanFactoryPostProcessor接口:

  public class MyContextWrapper implements ApplicationContextAware,
             BeanFactoryPostProcessor {

   private ApplicationContext appContext;
   private ConfigurableListableBeanFactory factory;

   public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
              throws BeansException {
   this.factory = factory;
   }
   public void setApplicationContext(ApplicationContext c)
            throws BeansException {
   this.appContext = c;   
   }

   //setters and getters

}

让 spring 通过在 XML 配置文件中声明 bean 来加载到它的上下文中:

<bean id="appContext" class="my.package.MyContextWrapper">
</bean>

现在,这个Bean可以通过引用它加载到应用程序的任何其他Bean中:

<bean id="myBeanFactory" class="my.package.MyBeanFactory">
 <property name="springContext" ref="appContext">
 </property>
</bean>

使用 GenericBeanDefinition 加载 Bean 定义:

BeanDefinitionRegistry registry = ((BeanDefinitionRegistry )factory);

GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(MyBeanClass.class);
beanDefinition.setLazyInit(false);
beanDefinition.setAbstract(false);
beanDefinition.setAutowireCandidate(true);
beanDefinition.setScope("session");

registry.registerBeanDefinition("dynamicBean",beanDefinition);

Bean 在会话作用域中创建,并将存储在用户会话中。属性自动连接候选项告诉 Spring,如果 Bean 的依赖项(如 setter 或 getter 或构造函数参数)应由 Spring 自动处理。属性 lazy init 告诉 Spring 是否需要在需要时实例化此 Bean。

要获取 Spring Bean 的句柄,请使用 Spring 应用程序上下文,如下所示:

Object bean= 
 getApplicationContext().getBean("dynamicBean");
 if(bean instanceof MyBeanClass){
 MyBeanClass myBean = (MyBeanClass) bean;

   // do with the bean what ever you have to do.
 } 

推荐