【问题标题】:Inject Spring bean in groovy bean在 groovy bean 中注入 Spring bean
【发布时间】:2014-06-18 07:17:03
【问题描述】:

我有带有 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"})

【问题讨论】:

  • 例如,如果您在 GitHub 上提供一个最小的工作示例,将更容易找到答案。

标签: java spring groovy


【解决方案1】:

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

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";
    }

}

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2013-06-25
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多