在Groovy bean中注入Spring bean

5

我有一个使用spring-boot-starter-remote-shell的Spring Boot应用程序。当我运行这个hello.groovy脚本时,它会打印“hello”,这是正常的。

package commands

import org.crsh.cli.Usage
import org.crsh.cli.Command

class hello {

    @Usage("Say Hello")
    @Command
    def main(InvocationContext context) {
        return "hello";
    }

}

但是当我尝试注入一些Spring bean时,它总是为空。

package commands

import org.crsh.cli.Usage
import org.crsh.cli.Command
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.batch.core.launch.JobLauncher

@Component
class hello {
    @Autowired
    JobLauncher jobLauncher;

    @Usage("Say Hello")
    @Command
    def main(InvocationContext context) {
        if(jobLauncher != null){
            return "OK";
        }else{
            return "NULL";
        }
        return "hello j";
    }

}

我有一个@ComponentScan(basePackages={"com....", "commands"})

该代码段是Spring框架中的注解,用于指示Spring在哪些包中寻找组件。在这个例子中,Spring将在"com...."和"commands"这两个包中寻找组件。

如果您在GitHub上提供一个最小的工作示例,那么找到答案会更容易。 - Opal
1个回答

3

可以从调用上下文中获取Spring BeanFactory。

package commands

import org.crsh.cli.Usage
import org.crsh.cli.Command
import org.crsh.command.InvocationContext;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.batch.core.launch.JobLauncher

class hello {

    @Usage("Say Hello")
    @Command
    def main(InvocationContext context) {
        BeanFactory beanFactory = (BeanFactory) context.getAttributes().get("spring.beanfactory");
        JobLauncher jobLauncher = beanFactory.getBean(JobLauncher.class);
        if(jobLauncher != null){
            return jobLauncher.toString();
        }else{
            return "NULL";
        }
        return "hello j";
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接