【发布时间】:2015-08-28 01:32:48
【问题描述】:
我有一个 Spring Boot 应用程序 (Y),它依赖于一组打包为 x.jar 并在应用程序 Y 的 pom.xml 中作为依赖项提及的库文件。
x.jar 有一个名为 (User.java) 的 bean 应用程序 Y 有一个名为 (Department.java) 的 java 类
当我尝试在 Department.java 中自动装配 User.java 的实例时,我收到以下错误
我不能 @Autowire 一个存在于依赖库 Jar 中的 Bean 吗?
无法自动装配字段:私人 com.User 用户;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 为依赖找到了类型为 [com.User] 的合格 bean:预期在 至少 1 个有资格作为自动装配候选者的 bean 依赖。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
没有为依赖找到类型为 [com.User] 的合格 bean:预期 至少 1 个 bean 有资格作为自动装配候选者 依赖。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)}**
这是 Spring Boot Application 'Y' 中的代码
package myapp;
@Component
public class Department {
@Autowired
private com.User user;
//has getter setters for user
}
这是库x.jar中User.java的代码
package com;
@Component
@ConfigurationProperties(prefix = "test.userproperties")
public class User {
private String name;
//has getter setters for name
}
这是应用Y的pom.xml中x.jar的依赖项
<groupId>com.Lib</groupId>
<artifactId>x</artifactId>
<version>001</version>
</dependency>
这是应用程序“Y”中的主类
@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableZuulProxy
@EnableGemfireSession(maxInactiveIntervalInSeconds=60)
@EnableCircuitBreaker
@EnableHystrixDashboard
@EnableDiscoveryClient
public class ZuulApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ZuulApplication.class).web(true).run(args);
}
}
Department 和 User 都在不同的包下。
解决方案:我应用了以下 2 个步骤,现在自动装配工作正常。
第一步:在jar文件中添加如下类
package com
@Configuration
@ComponentScan
public class XConfiguration {
}
第二步:在Y项目的主类中导入这个Configuration类
@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableZuulProxy
@EnableGemfireSession(maxInactiveIntervalInSeconds=60)
@EnableCircuitBreaker
@EnableHystrixDashboard
@EnableDiscoveryClient
@Import(XConfiguration.class)
public class ZuulApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ZuulApplication.class).web(true).run(args);
}
}
【问题讨论】:
-
请显示您的应用程序上下文。
-
你可能没有对该库的包进行组件扫描
-
我们没有使用应用程序上下文 XML,只使用了注释。应用 Y 是一个 Spring Boot 应用。
-
你说它是“bean”,但“bean”是什么意思?看起来它只是一个 POJO。您现在如何获得对它的引用?
-
那么,向我们展示您的配置类。用@Configuration 注释的那个。