簡體   English   中英

在groovy bean中注入Spring bean

[英]Inject Spring bean in groovy bean

我有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時,它總是為null。

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM