我有带有 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";
}
}
但是当我尝试注入(inject)一些 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 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";
}
}
关于java - 在 groovy bean 中注入(inject) Spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24279274/