簡體   English   中英

如何從外部目錄中的 jar 創建 bean

[英]How to create a bean from a jar in external directory

我有一個基本的 spring 應用程序,它只需加載一個 bean 就可以了。 我知道在項目中,我可以使用 class 中的注釋 @Component 將其標記為 bean,spring 應用程序將找到它並采取相應措施。

但是,我目前正在嘗試將組件放在外部目錄 /Users/me/plugin.jar 中的 jar 即 plugin.jar 中。 I am at a lost for how to get spring to search within that jar for an annotated class instead of the local package. 這甚至可能嗎?

I want to be able to load the bean from the jar without the jar being included in the class-path but rather by searching the directory for the jar and dynamically creating the bean based on whatever Jar is in there.

我已經使用 Java 反射和 URLClassLoader 從 jar 動態加載類,但無法弄清楚如何在 Spring 中做同樣的事情。 非常感謝任何有關如何開始的幫助或指導。 謝謝!

附加信息:spring 應用程序的設計目的是,當它運行時,它會掃描指定目錄中的任何 jars,如果它找到一個 jar,它會從其中創建一個類。 我無法找到如何讓 spring 應用程序搜索掃描指定目錄以將 jars 用作組件。 我發現的所有內容都只是引用項目中的類。

您可以創建一個配置,從外部 jar 啟動所需的 bean。

 @Configuration
    public class AppConfig {

        @Bean
        public MyBean myBean() {
            return new YourExternalClassName();
        }

    }

在配置 class 上使用@ComponentScan注釋,並指定外部組件的 package:

@Configuration
@ComponentScan(basePackages={"com.foo.bar"})
public class Config { }

您還可以在外部 jar 中定義元注釋:

@Retention(value=RUNTIME)
@Target(value=TYPE)
@ComponentScan(basePackages={"com.foo.bar"})
public @interface EnableExternalFoo { }

並將其應用於配置 class:

@Configuration
@EnableExternalFoo
public class Config { }

如果您的 plugin.jar 是帶有 @Component 的 Spring 項目,您只需掃描 package:

@ComponentScan(basePackages = {"com.exp"}, basePackageClasses = DependencyBasePackageClass.class)

//external.jar
package com.exp;

import org.springframework.stereotype.Component;

@Component
public class ExpBean {
}

如果 bean 只是 external.jar 中的 class,則可以創建 Factory 或 Singleton 並將其用作 Bean。

但是,我目前正在嘗試將組件放在外部目錄 /Users/me/plugin.jar 中的 jar 即 plugin.jar 中。 I am at a lost for how to get spring to search within that jar for an annotated class instead of the local package. 這甚至可能嗎?

您可以在運行時將 JAR 添加到應用程序的類路徑中。 但問題是在編譯時您還需要將 jar 作為編譯依賴項。
由於您使用 Spring Boot,這意味着您使用 Maven 或 Gradle 作為構建工具。
在這種情況下,您不必使用本地目錄來指定您的外部 jars,否則您的構建將只能在您的機器上和您機器的非常特定的 state 中重現(Z68995FCBF432492D1548ZD94DAC04 在指定的目錄中)。 您不想破壞構建工具的優勢。
更強大的方法是應用 maven/gradle 方式:
- 將 jar 定義為 maven/gradle 工件
- 將其推送到您的存儲庫(如果您使用它,則為本地和中央)
- 在應用程序的pom.xml / build.gradle的依賴項中聲明 jar

然后在您的應用程序中,您可以聲明在 JAR 中定義的Foo class 的 bean,例如:

@Configuration
public class ExternalBeanConfig {

        @Bean
        public Foo foo() {
            return new Foo();
        }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM