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

How to import a class from a Jenkins Shared Library into the pipeline

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

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

并且在管道的开头

library 'testlibrary@'
import ClassTest

结果:

WorkflowScript: 2: unable to resolve class ClassTest @line 2, column 1.
import ClassTest

之前,我只是去

library 'testlibrary@' _

并使用

的方法
script {
    libraryTest.method1()
    ...
    libraryTest.method2()
}

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

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

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

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

但现在错误是

unexpected token: package @ line 2

groovy 文件的前两行是:

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

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

在我使用的管道中加载库:

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

在class文件中,没有package指令。我想我不需要一个,因为我没有任何其他文件或 classes,所以我真的不需要一个包。此外,在 class 和 class 所在的文件中使用相同的名称时出现错误。该错误专门抱怨并要求更改其中一个。我猜这两件事与詹金斯有关。

有效,库已加载。

(也许它可以帮助别人)

我遇到了同样的问题。 一旦我在文件夹 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)

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

//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()