Spring Inject / AutoWire在运行时创建的Groovy类

时间:2013-02-19 12:51:39

标签: java spring groovy

我有一个执行Groovy脚本的Spring Controlled Grovoy Script Executor类。

如下所示

    final ClassLoader parent = getClass().getClassLoader();
    final GroovyClassLoader loader;

    loader = AccessController.doPrivileged(new PrivilegedAction<GroovyClassLoader>() {
        @Override
        public GroovyClassLoader run() {
            return new GroovyClassLoader(parent);
        }
    });


    this.groovyClass = loader.parseClass(" def returnSomthing() { return SpringControlledBean.action('Hello World') } ");
    final GroovyObject groovyObject = (GroovyObject) this.groovyClass.newInstance();
    final Object[] args = { };
    final Object result = groovyObject.invokeMethod("returnSomthing", args);

是否可以将 SpringControlledBean 注入脚本?通过也许是autowire,或者让Spring创建类的理解,因为脚本会改变,所以需要重新创建类?

如果类是类路径的一部分并且使用java构建,则可以进行自动装配,但是这个脚本内容在运行时已经过去了,因此春天不需要知道。

1 个答案:

答案 0 :(得分:1)

您需要一个AutowireCapableBeanFactory的实例,您可以通过将您的课程声明为BeanFactoryAware来获得,然后您可以调用方法autowireBean(existingBean)

例如:

class MyBeanCreator implements BeanFactoryAware {

  private AutowireCapableBeanFactory beanFactory; //you need to add setter as well

  def foobar() {
    //your existing code....
    final GroovyObject groovyObject = (GroovyObject) this.groovyClass.newInstance();

    //Wire with Spring 
    beanFactory.autowireBean(groovyObject);

    //rest of your existing code...
  }

}

另请参阅:http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html