【问题标题】:SpringBoot: Can I @Autowire Bean in runnable JAR from JAR provided using java -cp?SpringBoot:我可以使用 java -cp 提供的 JAR 中的可运行 JAR 中的 @Autowire Bean 吗?
【发布时间】:2017-08-10 22:57:31
【问题描述】:

我有包含接口的可运行 JAR A:

interface FooInterface {
    void foo();
    ...
}

在 JAR A 中,我还有一个试图自动装配 FooInterface 实现的类:

class Other{
    @Autowired 
    FooInterface fooInterfaceImplementation;
    ...
}

在其他项目 B 中,我将 jar A 作为外部库和 FooInterface 的实现:

@Component
class BarClass implements FooInterface {
    void foo(){...}
    ...
}

我正在尝试使用以下命令运行可运行的 A JAR,其中包含 JAR B 中的类:

java -jar A.jar -cp B.jar

但它以以下异常结束:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ocado.cfc.optimisation.AlgorithmInterface' available
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:348)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:335)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1093)
        at com.ocado.cfc.optimisation.Executable.main(Executable.java:81)

是否可以以这种方式自动装配所需的 bean?

任何帮助高度赞赏。

【问题讨论】:

    标签: java spring spring-boot jar autowired


    【解决方案1】:

    如果您尝试同时使用-jar-cp,这是不可能的。当您使用 -jar 时,-cp 会被忽略。

    如果你想在类路径中有多个 jar,你可以使用 -cp 传递它们。然后,您还必须提供要启动的主类的名称。鉴于您似乎正在使用 Spring Boot,可能看起来像这样:

    java -cp A.jar:B.jar org.springframework.boot.loader.JarLauncher
    

    您可能还对 Spring Boot 的 PropertiesLauncher 感兴趣,它允许您创建具有可配置类路径的可执行 jar。

    【讨论】:

      【解决方案2】:

      是的,为了从类路径 JAR 文件中检测/扫描 bean,您需要使用类级别注释 @ComponentScan(basePackages="com.ocado") 将包添加到您的 Spring Boot 启动器类。

      【讨论】:

        猜你喜欢
        • 2015-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-05
        • 2015-08-28
        • 2016-07-09
        • 1970-01-01
        • 2021-05-14
        相关资源
        最近更新 更多