Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Spring bean in groovy bean

I have Spring Boot application with spring-boot-starter-remote-shell. When I put this hello.groovy script it prints 'hello' and that's OK.

package commands

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

class hello {

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

}

But when I try to inject some Spring bean it's always 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";
    }

}

I have @ComponentScan(basePackages={"com....", "commands"})

like image 241
Evgeni Dimitrov Avatar asked Oct 21 '22 06:10

Evgeni Dimitrov


1 Answers

Spring BeanFactory can be taken from the Invocation context.

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

}
like image 115
Evgeni Dimitrov Avatar answered Oct 22 '22 23:10

Evgeni Dimitrov