How to use BeanFactoryPostProcessor to inject beans in java
使用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("数据查询成功..."); }
脚本运行结果:
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!

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

RuoYi framework circular dependency problem troubleshooting and solving the problem of circular dependency when using RuoYi framework for development, we often encounter circular dependency problems, which often leads to the program...

About SpringCloudAlibaba microservices modular development using SpringCloud...

Questions about a curve integral This article will answer a curve integral question. The questioner had a question about the standard answer to a sample question...

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

JDBC...

Why can't the main class be found after copying and pasting the package in IDEA? Using IntelliJIDEA...

State synchronization between Java multi-interface calls: How to ensure that interface A is called after it is executed? In Java development, you often encounter multiple calls...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)