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

Xet*_*ius 4 java spring

我正在动态创建包含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);
            }
    }
Run Code Online (Sandbox Code Playgroud)

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

Boz*_*zho 10

当你实例化类,它们都没有 Spring管理.Spring必须实例化类,以便它可以注入它们的依赖项.这与本案的异常,当您使用@Configurable<context:load-time-weaver/>,而这更是一个黑客,我会建议反对.

代替:

  • 制作范围的豆 prototype
  • 获取ApplicationContext(在网络应用程序中这是通过完成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);
Run Code Online (Sandbox Code Playgroud)

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