" />

欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java動(dòng)態(tài)腳本Groovy獲取Bean技巧

 更新時(shí)間:2021年12月14日 11:14:49   作者:南國(guó)以南i  
這篇文章主要給大家分享的是Java動(dòng)態(tài)腳本Groovy獲取Bean技巧,在Java代碼中當(dāng)我們需要一個(gè)Bean對(duì)象,通常會(huì)使用spring中@Autowired注解,用來(lái)自動(dòng)裝配對(duì)象。下面我們一起進(jìn)入文章學(xué)習(xí)個(gè)表格多 詳細(xì)內(nèi)容吧

Groovy中不能使用@Autowired(autowired是在spring啟動(dòng)后注入的,此時(shí)還未加載groovy代碼,故無(wú)法注入)

一、使用BeanFactoryPostProcessor注入Bean:

它與 BeanPostProcessor接口類似,可以對(duì)bean的定義(配置元數(shù)據(jù))進(jìn)行處理;也就是spring ioc運(yùn)行BeanFactoryPostProcessor在容器實(shí)例化任何其他的bean之前讀取配置元數(shù)據(jù),并有可能修改它;如果業(yè)務(wù)需要,可以配置多個(gè)BeanFactoryPostProcessor的實(shí)現(xiàn)類,通過(guò)"order"控制執(zhí)行次序(要實(shí)現(xiàn)Ordered接口)。

第一步:創(chuàng)建實(shí)現(xiàn)SpringUtils 接口工具(組件)來(lái)獲取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應(yīng)用上下文環(huán)境 \*/
    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;
    }
}

第二步:創(chuàng)建Groovy腳本裝載類,動(dòng)態(tài)解析腳本為Class

package com.example.groovy.testgroovy.task;

import groovy.lang.GroovyClassLoader;

public class GroovyUtils {

    private final static ClassLoader classLoader = GroovyUtils.class.getClassLoader();//獲取當(dāng)前類裝載器
    //ClassLoader:就是類的裝載器,它使JVM可以動(dòng)態(tài)的載入Java類,JVM并不需要知道從什么地方(本地文件、網(wǎng)絡(luò)等)載入Java類,這些都由ClassLoader完成。

    public final static GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader);
    //GroovyClassLoader:負(fù)責(zé)在運(yùn)行時(shí)編譯groovy源代碼為Class的工作,從而使Groovy實(shí)現(xiàn)了將groovy源代碼動(dòng)態(tài)加載為Class的功能。

    /**
     * .
     * 獲取實(shí)例化對(duì)象
     * @param script groovy腳本內(nèi)容
     * @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;
    }
}

第三步:讀取腳本內(nèi)容,執(zhí)行腳本

@Slf4j
@Component
public class CallAnalysisGroovyTask {


    /**
     * .
     * 讀取腳本內(nèi)容
     *
     * @return
     */
    public String getGroovy() {
        String context = "";
        try {
            String path = "E:\\IDEAFile\\testgroovy\\src\\main\\resources\\groovy\\LoadBean.groovy";
            context = FileUtils.readFileToString(new File(path));//將腳本內(nèi)容轉(zhuǎn)為字符串
        } catch (IOException e) {
            log.error("file is not found[{}]", e);
        }
        return context;
    }

    /**
     * .
     * 執(zhí)行g(shù)roovy腳本
     *
     * @param script
     */
    public void execGroovy(String script) {
        try {
            Runnable runnable = GroovyUtils.instanceTaskGroovyScript(script);//獲取實(shí)例對(duì)象
            runnable.run();//調(diào)用腳本方法
        } catch (Exception t) {
            log.error("execGroovy file {} error", script);
        }
    }
}

第四步:在resources目錄下創(chuàng)建.groovy文件

@Slf4j
class LoadBean implements Runnable {

    /**
     * .
     * Groovy獲取Bean
     */
    @Override
    void run() {
        log.info("Groovy開(kāi)始執(zhí)行,當(dāng)前類{}", this.getClass())
        ScriptService service = SpringUtils.getBean(ScriptService.class)
        log.info("ApplicationContext獲取對(duì)象[{}]", service.class)
        List<Script> item = service.findAll()//執(zhí)行bean中數(shù)據(jù)查詢方法
        for (Script s : item) {
            log.info("創(chuàng)建人:[{}],規(guī)則id:[{}],名稱:[{}]", s.getCreatePerson(), s.getRuleId(), s.getScriptName())
        }
        log.info("Groovy結(jié)束執(zhí)行,當(dāng)前類{}", this.getClass())
    }
}

第五步:實(shí)例化腳本,執(zhí)行方法?

   @GetMapping("/loadBean")
    public void loadBean(){
        String script = CallAnalysisGroovyTask.getGroovy(); //獲取腳本
        CallAnalysisGroovyTask.execGroovy(script);//實(shí)例化腳本,執(zhí)行方法
        log.info("數(shù)據(jù)查詢成功...");
    }


腳本運(yùn)行結(jié)果:

二、使用ApplicationContext注入Bean

它是springBeanFactory之外的另一個(gè)核心接口或容器,允許容器通過(guò)應(yīng)用程序上下文環(huán)境創(chuàng)建、獲取、管理bean。為應(yīng)用程序提供配置的中央接口。在應(yīng)用程序運(yùn)行時(shí)這是只讀的,但如果實(shí)現(xiàn)支持這一點(diǎn),則可以重新加載。

第一步:修改項(xiàng)目啟動(dòng)類,獲得ApplicationContext

@SpringBootApplication
public class TestgroovyApplication {

    //獲取應(yīng)用程序上下文環(huán)境
    private static ApplicationContext applicationContext;

    public static void main(String[] args) {
        applicationContext = SpringApplication.run(TestgroovyApplication.class, args);
    }

第二步:修改resources目錄下創(chuàng)建的.groovy文件

    /**
     * .
     * Groovy獲取Bean
     */
    @Override
    void run() {
        log.info("Groovy開(kāi)始執(zhí)行,當(dāng)前類{}", this.getClass())
        ScriptService service = TestgroovyApplication.applicationContext.getBean(ScriptService.class)
        log.info("ApplicationContext獲取對(duì)象[{}]", service.class)
        List<Script> item = service.findAll()//執(zhí)行bean中數(shù)據(jù)查詢方法
        for (Script s : item) {
            log.info("創(chuàng)建人:[{}],規(guī)則id:[{}],名稱:[{}]", s.getCreatePerson(), s.getRuleId(), s.getScriptName())
        }
        log.info("Groovy結(jié)束執(zhí)行,當(dāng)前類{}", this.getClass())
    }


腳本運(yùn)行結(jié)果:

到此這篇關(guān)于Java動(dòng)態(tài)腳本Groovy獲取Bean技巧的文章就介紹到這了,更多相關(guān)Java動(dòng)態(tài)腳本Groovy獲取Bean內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java使用Collections工具類對(duì)List集合進(jìn)行排序

    Java使用Collections工具類對(duì)List集合進(jìn)行排序

    這篇文章主要介紹了Java使用Collections工具類對(duì)List集合進(jìn)行排序,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • JAVA后臺(tái)轉(zhuǎn)換成樹(shù)結(jié)構(gòu)數(shù)據(jù)返回給前端的實(shí)現(xiàn)方法

    JAVA后臺(tái)轉(zhuǎn)換成樹(shù)結(jié)構(gòu)數(shù)據(jù)返回給前端的實(shí)現(xiàn)方法

    這篇文章主要介紹了JAVA后臺(tái)轉(zhuǎn)換成樹(shù)結(jié)構(gòu)數(shù)據(jù)返回給前端的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • Mybatis?selectKey 如何返回新增用戶的id值

    Mybatis?selectKey 如何返回新增用戶的id值

    這篇文章主要介紹了Mybatis?selectKey 如何返回新增用戶的id值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • break在scala和java中的區(qū)別解析

    break在scala和java中的區(qū)別解析

    這篇文章主要介紹了break在scala和java中的區(qū)別解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • Spring Cloud搭建eureka過(guò)程圖解

    Spring Cloud搭建eureka過(guò)程圖解

    這篇文章主要介紹了Spring Cloud搭建eureka過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • SpringMVC接收前臺(tái)傳遞過(guò)來(lái)的值的實(shí)例

    SpringMVC接收前臺(tái)傳遞過(guò)來(lái)的值的實(shí)例

    下面小編就為大家分享一篇SpringMVC接收前臺(tái)傳遞過(guò)來(lái)的值的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-03-03
  • JVM內(nèi)存結(jié)構(gòu):程序計(jì)數(shù)器、虛擬機(jī)棧、本地方法棧

    JVM內(nèi)存結(jié)構(gòu):程序計(jì)數(shù)器、虛擬機(jī)棧、本地方法棧

    JVM 基本上是每家招聘公司都會(huì)問(wèn)到的問(wèn)題,它們會(huì)這么無(wú)聊問(wèn)這些不切實(shí)際的問(wèn)題嗎?很顯然不是。由 JVM 引發(fā)的故障問(wèn)題,無(wú)論在我們開(kāi)發(fā)過(guò)程中還是生產(chǎn)環(huán)境下都是非常常見(jiàn)的
    2021-06-06
  • mybatis如何設(shè)置useGeneratedKeys=true

    mybatis如何設(shè)置useGeneratedKeys=true

    這篇文章主要介紹了mybatis如何設(shè)置useGeneratedKeys=true,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。
    2022-01-01
  • Java螺旋矩陣處理方法詳解

    Java螺旋矩陣處理方法詳解

    螺旋矩陣是指一個(gè)呈螺旋狀的矩陣,它的數(shù)字由第一行開(kāi)始到右邊不斷變大,向下變大,向左變大,向上變大,如此循環(huán)。利用java實(shí)現(xiàn)的螺旋矩陣,當(dāng)輸入N之后,會(huì)自動(dòng)打印出螺旋矩陣
    2022-09-09
  • Java中的StringBuilder類解析

    Java中的StringBuilder類解析

    這篇文章主要介紹了Java中的StringBuilder類解析,該類被設(shè)計(jì)用作StringBuffer的一個(gè)簡(jiǎn)易替換,用在字符串緩沖區(qū)被單線程使用的時(shí)候,如果可能,優(yōu)先采用該類,因?yàn)樵诖蠖鄶?shù)實(shí)現(xiàn)中,String Builder比StringBuffer要快,需要的朋友可以參考下
    2023-09-09

最新評(píng)論