In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the skill of Java dynamic script Groovy to obtain Bean". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
@ Autowired cannot be used in Groovy (autowired is injected after spring startup, and groovy code is not loaded at this time, so it cannot be injected)
Use BeanFactoryPostProcessor to inject Bean:
It is similar to the BeanPostProcessor interface, it can deal with the definition of bean (configuration metadata); that is, spring ioc runs BeanFactoryPostProcessor to read configuration metadata before any other bean is instantiated by the container, and it is possible to modify it; if business needs, you can configure multiple BeanFactoryPostProcessor implementation classes to control the execution order through "order" (to implement the Ordered interface).
Step 1: create a tool (component) that implements the SpringUtils interface to get 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;@Componentpublic class SpringUtils implements BeanFactoryPostProcessor {/ * * Spring application context\ * / private static ConfigurableListableBeanFactory beanFactory; @ Override public void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) throws BeansException {SpringUtils.beanFactory = beanFactory } @ SuppressWarnings ("unchecked") public static T 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;}} step 2: create a Groovy script to load the class, and the dynamic parsing script is Class
Package com.example.groovy.testgroovy.task;import groovy.lang.GroovyClassLoader;public class GroovyUtils {private final static ClassLoader classLoader = GroovyUtils.class.getClassLoader (); / / get the current class loader / / ClassLoader: the class loader, which enables JVM to load Java classes dynamically. JVM does not need to know where to load Java classes (local files, networks, etc.), all done by ClassLoader. Public final static GroovyClassLoader groovyClassLoader = new GroovyClassLoader (classLoader); / / GroovyClassLoader: responsible for compiling the groovy source code to Class at run time, thus enabling Groovy to dynamically load the groovy source code into Class. / *. * get the instantiated object * @ param script groovy script content * @ 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;}} step 3: read the script content and execute the script
@ Slf4j@Componentpublic class CallAnalysisGroovyTask {/ *. * read script content * * @ return * / public String getGroovy () {String context = ""; try {String path = "E:\\ IDEAFile\\ testgroovy\\ src\\ main\\ resources\\ groovy\\ LoadBean.groovy"; context = FileUtils.readFileToString (new File (path)) / / convert the content of the script to a string} catch (IOException e) {log.error ("file is not found [{}]", e);} return context;} / * *. * execute groovy script * * @ param script * / public void execGroovy (String script) {try {Runnable runnable = GroovyUtils.instanceTaskGroovyScript (script); / / get instance object runnable.run (); / / call script method} catch (Exception t) {log.error ("execGroovy file {} error", script) Step 4: create a .groovy file in the resources directory
@ Slf4jclass LoadBean implements Runnable {/ *. * Groovy acquires Bean * / @ Override void run () {log.info ("Groovy starts execution, current class {}", this.getClass () ScriptService service = SpringUtils.getBean (ScriptService.class) log.info ("ApplicationContext gets object [{}]" Service.class) List item = service.findAll () / execute data query method for (Script s: item) {log.info ("Creator: [{}], Rule id: [{}], name: [{}]", s.getCreatePerson (), s.getRuleId (), s.getScriptName ())} log.info ("Groovy ends execution, current class {}" This.getClass ()}} step 5: instantiate the script Execute the method @ GetMapping ("/ loadBean") public void loadBean () {String script = CallAnalysisGroovyTask.getGroovy () / / get the script CallAnalysisGroovyTask.execGroovy (script); / / instantiate the script and execute the method log.info ("data query succeeded...");}
The result of running the script:
Second, use ApplicationContext to inject Bean
It is another core interface or container of spring in addition to BeanFactory, which allows the container to create, obtain, and manage bean through the application context. Provides a configured central interface for the application. This is read-only when the application is running, but can be reloaded if the implementation supports this.
Step 1: modify the project startup class to get ApplicationContext
@ SpringBootApplicationpublic class TestgroovyApplication {/ / get the application context private static ApplicationContext applicationContext; public static void main (String [] args) {applicationContext = SpringApplication.run (TestgroovyApplication.class, args);} step 2: modify the .groovy file created in the resources directory
/ *. * Groovy acquires Bean * / @ Override void run () {log.info ("Groovy starts execution, current class {}", this.getClass () ScriptService service = TestgroovyApplication.applicationContext.getBean (ScriptService.class) log.info ("ApplicationContext gets object [{}]" Service.class) List item = service.findAll () / execute data query method for (Script s: item) {log.info ("Creator: [{}], Rule id: [{}], name: [{}]", s.getCreatePerson (), s.getRuleId (), s.getScriptName ())} log.info ("Groovy ends execution, current class {}" This.getClass ()}
The result of running the script:
This is the end of the content of "what is the skill of Java dynamic script Groovy to get Bean". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.