【发布时间】:2019-06-14 00:00:34
【问题描述】:
我有一个 Spring Boot 项目,我无法从 外部 jar 中获取要自动装配的组件。当我尝试这样做时,我收到了 org.springframework.beans.factory.NoSuchBeanDefinitionException 说找不到具有该名称的 bean。
我尝试了一些在类似问题中找到的解决方案,例如:
How to autowire @service from external Jar in Spring
Spring Boot @autowired does not work, classes in different package
How can I @Autowire a spring bean that was created from an external jar?
..但仍然无法使其正常工作。
这是我想要完成的一个示例:
这里是Spring Boot项目中的boot class spring-project-example
package com.springdi.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import com.dependency.example.DependencyBasePackageClass;
import com.dependency.example.somepackage.SomeBean;
@SpringBootApplication
@ComponentScan(basePackages = {"com.springdi.example"}, basePackageClasses = DependencyBasePackageClass.class)
public class SpringProjectExampleApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SpringProjectExampleApplication.class, args);
String beanName = SomeBean.class.getName();
System.out.printf("%s can be autowired: %s\n", beanName, String.valueOf(context.containsBean(beanName)).toUpperCase());
}
}
这只是一个简单的 Spring Boot 项目,检查是否可以自动装配依赖项 jar 中存在的组件。
这是jar中的组件(dependency-example-1.0.0.jar)
package com.dependency.example.somepackage;
import org.springframework.stereotype.Component;
@Component
public class SomeBean {
public void someMethod() {
System.out.println("Some process...");
}
}
这是同一个jar的基础包类
package com.dependency.example;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Just a class to serve as the root for component
* scanning in "com.dependency.example" and its sub-packages
*/
@Configuration
@ComponentScan
public class DependencyBasePackageClass {
}
我已经在 SpringProjectExampleApplication 和 @ComponentScan 中尝试过 @Import(DependencyBasePackageClass.class) 和 basePackages 和 basePackageClasses,但没有成功。
我也尝试过使用@SpringBootApplication(scanBasePackageClasses = {SpringProjectExampleApplication.class, DependencyBasePackageClass.class})
还有不安全的@SpringBootApplication(scanBasePackages = {"com.springdi.example", "com.dependency.example"})。
@Configuration @ComponentScan({"com.dependency.example"}) 也失败,context.containsBean("com.dependency.example.somepackage.SomeBean") 仍然返回 false。
这个 jar 包含在类路径和 pom.xml 中作为依赖项
<dependencies>
<!-- other dependencies -->
<dependency>
<groupId>com.rbaggio</groupId>
<artifactId>dependency-example</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${basedir}/lib/dependency-example-1.0.0.jar</systemPath>
</dependency>
</dependencies>
可能是 jar 的位置、包含方式还是需要一些额外的配置?
如果有任何帮助,我将不胜感激!提前致谢。
【问题讨论】:
-
@ComponentScan阻碍了找到该依赖 bean。执行@Import或创建一个返回依赖项目的bean。
标签: java spring maven spring-boot