如何将类从 Jenkins 共享库导入管道



我在共享库的/var 目录中使用了一些全局方法,一切正常。现在我需要保持进程的状态,所以我正在编写一个时髦的类。 基本上我在"/src"中有一个名为"ClassTest.groovy"的类,它是这样的;

class ClassTest {
String testString
def method1() { ... }
def method2() { ... }
}

在管道的开头

library 'testlibrary@'
import ClassTest

结果:

工作流脚本:2:无法解析类测试@line 2,第 1 列。
导入类测试

以前,我只是去

library 'testlibrary@' _

并将方法用作

script {
libraryTest.method1()
...
libraryTest.method2()
}

其中方法在文件'/var/libraryTest.groovy'中,一切正常。所以我知道共享库在那里,但我对 groovy/Jenkins 处理类/共享库的方式感到困惑。

导入类的正确方法是什么?我在文档中找不到一个简单的示例(带有时髦的文件、文件结构和管道(。

编辑: 我将文件移动到"src/com/company/ClassTest.groovy"并将管道修改为

@Library('testlibrary@') import com.company.ClassTest
def notification = new ClassTest()

但现在错误是

意外令牌:包 @ 行 2

Groovy文件的前两行是:

// src/com/company/ClassTest.groovy
package com.company;

到目前为止,这就是我发现的。

要在我使用的管道中加载库,请执行以下操作:

@Library('testlibrary@') import com.company.ClassTest
def notification = new ClassTest()

在类文件中,没有指令。我想我不需要一个,因为我没有任何其他文件或类,所以我真的不需要包。此外,在对类和类所在的文件使用相同的名称时,我遇到了错误。该错误特别抱怨并要求更改其中一个。我想这两件事与詹金斯有关。

这有效,并且库已加载。

(也许它可以帮助其他人(

我遇到了同样的问题。 一旦我在文件夹com/lib/中添加了一个package-info.java,其中包含

/**
* com.lib package 
*/
package com.lib;

并在每个文件的第一行添加package com.lib,它开始工作。

我遇到了同样的问题。 经过对 Jenkins 文档的一些试验和错误。(https://www.jenkins.io/doc/book/pipeline/shared-libraries/#using-libraries(

我发现当我想从我拥有的共享库中导入一个类时,我需要这样做:

//thanks to '_', the classes are imported automatically.
// MUST have the '@' at the beginning, other wise it will not work.
@Library('my-shared-library@BRANCH') _ 
// only by calling them you can tell if they exist or not.
def exampleObject = new example.GlobalVars() 
// then call methods or attributes from the class.
exampleObject.runExample()

最新更新