gpt4 book ai didi

java - 我不能 @Autowire 一个存在于依赖库 Jar 中的 Bean 吗?

转载 作者:IT老高 更新时间:2023-10-28 13:57:23 30 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序 (Y),它依赖于一组打包为 x.jar 的库文件,并在应用程序 Y 的 pom.xml 中作为依赖项提及。

x.jar 有一个名为 (User.java) 的 bean应用程序 Y 有一个名为 (Department.java) 的 java 类

当我尝试在 Department.java 中 Autowiring User.java 的实例时,我收到以下错误

我不能 @Autowire 一个存在于依赖库 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 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 个步骤,现在 Autowiring 工作正常。

第一步:在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);
}
}

最佳答案

您需要添加主类和 User 类的包名才能 100% 确定,但更有可能的是,User 类不在您的主类的同一个包(或子包)中。这意味着组件扫描不会拾取它。

你可以强制 spring 像这样查看其他包:

@ComponentScan(basePackages = {"org.example.main", "package.of.user.class"})

关于java - 我不能 @Autowire 一个存在于依赖库 Jar 中的 Bean 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30796306/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com