我有一个Spring Boot应用程序(Y),它依赖于一组打包为x.jar的库文件,并在应用程序Y的pom.xml中作为依赖项提到 .
x.jar有一个名为(User.java)的bean应用程序Y有一个名为(Department.java)的java类
当我尝试在Department.java中自动装配User.java的实例时,我收到以下错误
Can't I @Autowire a Bean which is present in a dependent Library Jar ?
无法自动装配字段:private com.User user;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型[com.User]的限定bean:期望至少有1个bean符合此依赖项的autowire候选者 . 依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}没有找到类型[com.User]的限定bean用于依赖:预期至少有1个bean符合此依赖关系的autowire候选者 . 依赖注释:{@ 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的依赖项
com.Lib
x
001
这是应用程序'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);
}
}
部门和用户都在不同的包装下 .
Solution: I applied the following 2 steps and now the Autowiring is working fine.
第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);
}
}