![](/img/trans.png)
[英]How can I @Autowire a spring bean that was created from an external jar?
[英]SpringBoot: Can I @Autowire Bean in runnable JAR from JAR provided using java -cp?
我有包含界面的可运行JAR A:
interface FooInterface {
void foo();
...
}
在JAR AI中,还有一个类试图自动装配FooInterface实现:
class Other{
@Autowired
FooInterface fooInterfaceImplementation;
...
}
在其他项目BI中,将jar A作为外部库和FooInterface的实现:
@Component
class BarClass implements FooInterface {
void foo(){...}
...
}
我正在尝试使用以下命令,使用JAR B中的类运行可运行的A JAR:
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?
任何帮助,高度赞赏。
是的,为了让Spring从类路径JAR文件中检测/扫描bean,您需要使用类级别注释@ComponentScan(basePackages="com.ocado")
将包添加到spring boot启动器类中。
如果尝试同时使用-jar
和-cp
,则不可能。 使用-jar
时-cp
被忽略。
如果要在类路径上有多个jar,可以使用-cp
将它们都传递给它们。 然后,您还必须提供要启动的主类的名称。 假设您似乎正在使用Spring Boot,则可能看起来像这样:
java -cp A.jar:B.jar org.springframework.boot.loader.JarLauncher
您可能还对Spring Boot的PropertiesLauncher
感兴趣,该PropertiesLauncher
使您可以创建带有可配置类路径的可执行jar。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.