代码之家  ›  专栏  ›  技术社区  ›  Xetius

在动态创建的类中实例化SpringBean

  •  4
  • Xetius  · 技术社区  · 14 年前

    我正在动态地创建包含SpringBean的类,但是bean没有被实例化或初始化,因此它们为空。

    如何确保一个动态创建的类正确地创建它的所有SpringBean?

    这就是我动态创建类的方式:

    Class ctransform;
    try {
        ctransform = Class.forName(strClassName);
        Method handleRequestMethod = findHandleRequestMethod(ctransform);
        if (handleRequestMethod != null) {
            return (Message<?>) handleRequestMethod.invoke(ctransform.newInstance(), message);
                }
        }
    

    这样,ctransform(strClassName类型)中的所有SpringBean对象都将保留为空。

    2 回复  |  直到 14 年前
        1
  •  10
  •   Bozho    14 年前

    每当实例化类时,它们都是 春天来了。Spring必须实例化类,以便它可以注入它们的依赖项。这是你使用时的例外情况 @Configurable <context:load-time-weaver/> 但这更像是一个黑客,我建议你不要这么做。

    而是:

    • 做范围之豆 prototype
    • 获得 ApplicationContext (在Web应用程序中,这是通过 WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) )
    • 如果这些类没有注册(我假设它们没有注册),请尝试强制转换为 StaticApplicationContext (我不确定这是否可行),然后打电话 registerPrototype(..) 在上下文中注册类。如果不起作用,使用 GenericContext 及其 registerBeanDefinition(..)
    • 获取与类型匹配的所有实例,使用 appContext.getBeansOfType(yourclass) ;或者,如果您只是注册了它并知道它的名称-使用 appContext.getBean(name)
    • 决定哪一个适用。通常您在 Map 所以用它吧。

    但我通常会避免对春豆的思考——应该有另一种方法来实现这个目标。


    更新: 我只是想到了一个更简单的解决方案,如果您不需要注册be an的话,这个解决方案就可以工作——也就是说,动态生成的类不会被注入到任何其他动态生成的类中:

    // using WebApplicationContextUtils, for example
    ApplicationContext appContext = getApplicationContext(); 
    Object dynamicBeanInstance = createDyamicBeanInstance(); // your method here
    appContext.getAutowireCapableBeanFactory().autowireBean(dynamicBeanInsatnce);
    

    您将设置依赖项,而不将新类注册为bean。

        2
  •  0
  •   Snehal    14 年前

    您需要Spring容器来实例化类,而不是使用反射来实例化。要使bean范围为原型,请使用以下语法:

    <bean id="prototypeBean" class="xyz.PrototypeBean" scope="prototype">
      <!-- inject dependencies here as required -->
    </bean>
    

    然后使用以下代码实例化原型bean:

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext ( "applicationContext.xml" );
    
    PrototypeBean prototypeBean = ( PrototypeBean ) applicationContext.getBean ( "prototypeBean" );