开发者

What is the best way to import constants into a groovy script?

开发者 https://www.devze.com 2023-01-18 19:34 出处:网络
I have been setting up a scripting envrionment using Groovy.I have a groovy script called FrameworkiDatabase.groovy which contains a class of the same name.This works fine.I also have another file cal

I have been setting up a scripting envrionment using Groovy. I have a groovy script called FrameworkiDatabase.groovy which contains a class of the same name. This works fine. I also have another file called connections.groovy which contains maps like the following:

SUPPORT2=[
 host:"host.name", 
 port:"1521", 
 db:"support2",  
 username:"username", 
 password:"password", 
 dbType:"oracle"
]

This holds a collection of database bookmarks, a bit like an oracle tnsnames file, so I don't need to remember all the parameters when connecting to databases.

When using groovysh, I can import this using the load command, and it is available in current scope. How can I load it as part of a script the same way? It has no class definition around it - does it need one? I have tried doing that, and adding a static import, but that didn't work...

I tried something like this, but no luck:

testFrameworkiDatabase.groovy:

import static connections
def db = new FrameworkiDatabase(SUPPORT2)

db.listInvalidObjects()
db.getDBSchemaVersion()
db.getFWiVersion() 
db.getSPVersion()
db.getFileloaderVersion()
db.ge开发者_StackOverflow中文版tAdminToolVersion()
db.getReportsVersion()

So I want to load those connections as constants - is there any way I can do this easily?


Not sure if it's the best way, but one way would be to write this into Connections.groovy

class Connections {
  static SUPPORT2 = [
    host:"host.name", 
    port:"1521", 
    db:"support2",  
    username:"username", 
    password:"password", 
    dbType:"oracle"
  ]
}

Then, compile this with groovyc Connections.groovy to generate a class file

Then, in your test script or on the groovysh prompt, you can do:

import static Connections.*

println SUPPORT2

To get the output:

[host:host.name, port:1521, db:support2, username:username, password:password, dbType:oracle]

If compiling the Connections.groovy class isn't good enough, I think you're going to be looking at loading the source into a Binding object by using one of the Groovy embedding techniques

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号