它与BeanPostProcessor
接口类似,可以对bean的定义(配置元数据)进行处理;也就是spring ioc
运行BeanFactoryPostProcessor在容器实例化任何其他的bean之前读取配置元数据,并有可能修改它;如果业务需要,可以配置多个BeanFactoryPostProcessor的实现类,通过"order"控制执行次序(要实现Ordered接口)。
import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.stereotype.Component; @Component public class SpringUtils implements BeanFactoryPostProcessor { /** Spring应用上下文环境 \*/ private static ConfigurableListableBeanFactory beanFactory; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { SpringUtils.beanFactory = beanFactory; } @SuppressWarnings("unchecked") public staticT getBean(String name) throws BeansException { return (T) beanFactory.getBean(name); } public static T getBean(Class clz) throws BeansException { T result = (T) beanFactory.getBean(clz); return result; } }
package com.example.groovy.testgroovy.task; import groovy.lang.GroovyClassLoader; public class GroovyUtils { private final static ClassLoader classLoader = GroovyUtils.class.getClassLoader();//获取当前类装载器 //ClassLoader:就是类的装载器,它使JVM可以动态的载入Java类,JVM并不需要知道从什么地方(本地文件、网络等)载入Java类,这些都由ClassLoader完成。 public final static GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader); //GroovyClassLoader:负责在运行时编译groovy源代码为Class的工作,从而使Groovy实现了将groovy源代码动态加载为Class的功能。 /** * . * 获取实例化对象 * @param script groovy脚本内容 * @param* @return * @throws IllegalAccessException * @throws InstantiationException */ public static T instanceTaskGroovyScript(String script) throws IllegalAccessException, InstantiationException { Class taskClz = groovyClassLoader.parseClass(script); T instance = (T) taskClz.newInstance(); return instance; } }
@Slf4j @Component public class CallAnalysisGroovyTask { /** * . * 读取脚本内容 * * @return */ public String getGroovy() { String context = ""; try { String path = "E:\\IDEAFile\\testgroovy\\src\\main\\resources\\groovy\\LoadBean.groovy"; context = FileUtils.readFileToString(new File(path));//将脚本内容转为字符串 } catch (IOException e) { log.error("file is not found[{}]", e); } return context; } /** * . * 执行groovy脚本 * * @param script */ public void execGroovy(String script) { try { Runnable runnable = GroovyUtils.instanceTaskGroovyScript(script);//获取实例对象 runnable.run();//调用脚本方法 } catch (Exception t) { log.error("execGroovy file {} error", script); } } }
@Slf4j class LoadBean implements Runnable { /** * . * Groovy获取Bean */ @Override void run() { log.info("Groovy开始执行,当前类{}", this.getClass()) ScriptService service = SpringUtils.getBean(ScriptService.class) log.info("ApplicationContext获取对象[{}]", service.class) List