Java動態腳本Groovy讀取配置文件
- 2021 年 12 月 15 日
- 筆記
- Java開發, Spring Boot
前言:請各大網友尊重本人原創知識分享,謹記本人部落格:南國以南i
核心涉及:
@Value:作用是通過註解將常量、配置文件中的值、其他bean的屬性值注入到變數中,作為變數的初始值。
@Configuration:用於定義配置類,可替換xml配置文件,標註在類上,相當於把該類作為spring的xml配置文件中的<beans>,作用為:配置spring容器(應用上下文)。
ApplicationContext:它是spring繼BeanFactory之外的另一個核心介面或容器,允許容器通過應用程式上下文環境創建、獲取、管理bean。為應用程式提供配置的中央介面。在應用程式運行時這是只讀的,但如果實現支援這一點,則可以重新載入。
第一步:在yml中添加屬性值
#yml自定義屬性 basic: name: robin password: 123456 address: 上海市黃浦區
第二步:創建裝配工具類
@Data @Configuration//定義配置類 public class ConfUtils { @Value("${basic.name}") private String name; @Value("${basic.password}") private String password; @Value("${basic.address}") private String address; }
第三步:Groovy腳本獲取Bean,讀取yml屬性值
友情鏈接:Groovy獲取Bean兩種方式你過來呀!
@Slf4j class LoadBean implements Runnable { private String name; private String password; private String address; /** * . * Groovy獲取Bean */ @Override void run() { log.info("Groovy開始執行,當前類{}", this.getClass()) ConfUtils conf = TestgroovyApplication.applicationContext.getBean(ConfUtils.class) this.name = conf.getName() this.password = conf.password this.address = conf.getAddress() log.info("姓名:[{}],密碼:[{}],地址:[{}]", name, password, address) log.info("Groovy結束執行,當前類{}", this.getClass()) } }