我有一個Spring Boot應用程序(Y),它依賴於一組庫文件打包爲x.jar,並在應用程序Y的pom.xml中作爲依賴項提到。Can not I @Autowire a Bean which is present in a dependent Library Jar?
x.jar有一個名爲bean (User.java) 應用Y具有命名(Department.java)的Java類
雖然我嘗試自動裝配裏面Department.java User.java的實例,我得到以下錯誤
燦我是否@Autowire存在於依賴庫Jar中的Bean?
無法自動填充字段:private com.User user;嵌套的異常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:否 依賴關係找到[com.User]類型的合格bean:預計在 至少1個符合此 依賴關係的候選資格的Bean。依賴註解: {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}
類型[com.User]的任何合格的豆找到依賴性:預期 至少1豆,其有資格作爲這個 依賴關係的autowire候選者。依賴註解: {@ org.springframework.beans.factory.annotation.Autowired(所需=真)} **
這裏是在Spring引導應用程序 'Y'
package myapp;
@Component
public class Department {
@Autowired
private com.User user;
//has getter setters for user
}
代碼這裏是User.java的庫中的代碼x.jar
package com;
@Component
@ConfigurationProperties(prefix = "test.userproperties")
public class User {
private String name;
//has getter setters for name
}
這是在應用的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);
}
}
兩個系主類和用戶都在不同的包。
解決方案:我應用以下2個步驟,現在自動裝配工作正常。
第1步:添加了以下類的jar文件
package com
@Configuration
@ComponentScan
public class XConfiguration {
}
步驟2:在Y項目的主類
@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);
}
}
顯示你的應用程序上下文請。 – Jens
您可能沒有對該庫的包進行組件掃描 –
我們還沒有使用應用上下文XML,只有註釋。應用程序Y是一個Spring Boot應用程序。 – yathirigan