简体   繁体   English

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

[英]Spring Inject/AutoWire a Groovy Class that is created at runtime

I have a Spring Controlled Grovoy Script Executor class that executes a Groovy Script. 我有一个执行Groovy脚本的Spring受控Grovoy脚本执行器类。

Something like below 像下面这样

    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);

Is it possible to inject the SpringControlledBean in to the script ? 是否可以将SpringControlledBean注入脚本? via maybe a autowire, or get Spring to create the class understanding that the class will need to be recreated as the script will change? 通过自动连线,还是让Spring创建类,以了解随着脚本的更改需要重新创建该类?

Autowire is possible if the class was part of the classpath and built with the java, but this script content is past at runtime, so not static for spring to know about. 如果该类是类路径的一部分并使用Java构建,则可以使用自动装配,但是此脚本内容在运行时已过去,因此对于Spring来说不是静态的。

You need an instance of AutowireCapableBeanFactory , that you can get by declaring your class as a BeanFactoryAware , and then you can call method autowireBean(existingBean) . 您需要一个AutowireCapableBeanFactory实例,可以通过将您的类声明为BeanFactoryAware来获得,然后可以调用方法autowireBean(existingBean)

For example: 例如:

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...
  }

}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM