在动态创建的类中实例化spring bean

我正在动态创建包含spring bean的类,但是bean没有被实例化或初始化,而是将它们保留为null。

如何确保动态创建的类正确创建其所有的spring bean?

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

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

这使得ctransform(strClassName类型)中的所有spring bean对象都为null。

无论何时实例化类,它们都不是由Spring管理的。 Spring必须实例化类,以便它可以注入它们的依赖项。 除了你使用@Configurable ,但这更像是一个黑客,我建议反对它。

代替:

  • 制作范围prototype的bean
  • 获取ApplicationContext (在Web应用程序中,这是通过WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
  • 如果类没有注册(我认为它们不是),请尝试转换为StaticApplicationContext (我不确定这是否可行),并调用registerPrototype(..)在上下文中注册您的类。 如果这不起作用,请使用GenericContext及其registerBeanDefinition(..)
  • 使用appContext.getBeansOfType(yourclass)获取与您的类型匹配的所有实例; 或者如果你刚刚注册并知道它的名字 – 只使用appContext.getBean(name)
  • 决定哪一个适用。 通常, Map只有一个条目,因此请使用它。

但我通常会避免反思春豆 – 应该有另一种方法来实现目标。


更新:我只想到一个更简单的解决方案,如果您不需要注册bean,那将会有效 – 即您的动态生成的类不会被注入任何其他动态生成的类:

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

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

您需要Spring容器来实例化类,而不是使用reflection来实例化。 要使bean作用于原型,请使用以下语法:

    

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

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