java – 我不能@Autowire一个依赖的Library Jar中存在的Bean吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 我不能@Autowire一个依赖的Library Jar中存在的Bean吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2568字,纯文字阅读大概需要4分钟。
内容图文
![java – 我不能@Autowire一个依赖的Library Jar中存在的Bean吗?](/upload/InfoBanner/zyjiaocheng/700/cf169fce96ff4e1a8b9c061865b0acbd.jpg)
我有一个Spring Boot应用程序(Y),它依赖于一组打包为x.jar的库文件,并在应用程序Y的pom.xml中作为依赖项提到.
x.jar有一个名为(User.java)的bean
应用程序Y有一个名为(Department.java)的java类
当我尝试在Department.java中自动装配User.java的实例时,我收到以下错误
我不能@Autowire存在于依赖的Library Jar中的Bean吗?
Could not autowire field: private com.User user; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.User] found for dependency: expected at
least 1 bean which qualifies as autowire candidate for this
dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}No qualifying bean of type [com.User] found for dependency: expected
at least 1 bean which qualifies as autowire candidate for this
dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}**
这是Spring Boot应用程序’Y’中的代码
package myapp;
@Component
public class Department {
@Autowired
private com.User user;
//has getter setters for user
}
这是Library 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’中的Main类
@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);
}
}
部门和用户都在不同的包装下.
解决方案:我应用了以下两个步骤,现在自动装配工作正常.
第1步:在jar文件中添加以下类
package com
@Configuration
@ComponentScan
public class XConfiguration {
}
第2步:在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);
}
}
解决方法:
您需要将主类和User类的包名称添加为100%确定,但更可能的是,User类不在主类的相同包(或子包)中.这意味着组件扫描不会拾取它.
您可以强制spring查看其他包,如下所示:
@ComponentScan(basePackages = {"org.example.main", "package.of.user.class"})
内容总结
以上是互联网集市为您收集整理的java – 我不能@Autowire一个依赖的Library Jar中存在的Bean吗?全部内容,希望文章能够帮你解决java – 我不能@Autowire一个依赖的Library Jar中存在的Bean吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。