Home  >  Article  >  Java  >  How to use BeanFactoryPostProcessor to inject beans in java

How to use BeanFactoryPostProcessor to inject beans in java

WBOY
WBOYforward
2023-04-19 18:31:121564browse

使用BeanFactoryPostProcessor注入Bean:

它与 BeanPostProcessor接口类似,可以对bean的定义(配置元数据)进行处理;也就是spring ioc运行BeanFactoryPostProcessor在容器实例化任何其他的bean之前读取配置元数据,并有可能修改它;如果业务需要,可以配置多个BeanFactoryPostProcessor的实现类,通过"order"控制执行次序(要实现Ordered接口)。

第一步:创建实现SpringUtils 接口工具(组件)来获取spring bean

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 static <T> T getBean(String name) throws BeansException
    {
        return (T) beanFactory.getBean(name);
    }
    public static <T> T getBean(Class<T> clz) throws BeansException
    {
        T result = (T) beanFactory.getBean(clz);
        return result;
    }
}

第二步:创建Groovy脚本装载类,动态解析脚本为Class

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 <T>
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T> 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);
        }
    }
}

第四步:在resources目录下创建.groovy文件

@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<Script> item = service.findAll()//执行bean中数据查询方法
        for (Script s : item) {
            log.info("创建人:[{}],规则id:[{}],名称:[{}]", s.getCreatePerson(), s.getRuleId(), s.getScriptName())
        }
        log.info("Groovy结束执行,当前类{}", this.getClass())
    }
}

第五步:实例化脚本,执行方法 

   @GetMapping("/loadBean")
    public void loadBean(){
        String script = CallAnalysisGroovyTask.getGroovy(); //获取脚本
        CallAnalysisGroovyTask.execGroovy(script);//实例化脚本,执行方法
        log.info("数据查询成功...");
    }

脚本运行结果:

How to use BeanFactoryPostProcessor to inject beans in java

The above is the detailed content of How to use BeanFactoryPostProcessor to inject beans in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete