I have a Spring Boot application (Y) which relies upon a set of Library files packed as x.jar and mentioned as a dependency in the pom.xml of the application Y.
x.jar has a bean named (User.java) Application Y has a java class named (Department.java)
While i try to Autowire an instance of User.java inside Department.java, i get the following error
Can't I @Autowire a Bean which is present in a dependent Library Jar ?
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)}**
Here is the code in the Spring Boot Application 'Y'
package myapp;
@Component
public class Department {
@Autowired
private com.User user;
//has getter setters for user
}
Here is the code of User.java in the Library x.jar
package com;
@Component
@ConfigurationProperties(prefix = "test.userproperties")
public class User {
private String name;
//has getter setters for name
}
This is the dependency entry for x.jar in the pom.xml of application Y
<groupId>com.Lib</groupId>
<artifactId>x</artifactId>
<version>001</version>
</dependency>
This is the Main class in the Application '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);
}
}
Both Department and User are under different packages.
Solution: I applied the following 2 steps and now the Autowiring is working fine.
Step 1: Added the following class in the jar file
package com
@Configuration
@ComponentScan
public class XConfiguration {
}
Step 2: Imported this Configuration class in the Y project's main class
@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);
}
}
You would need to add the package names of your main class and the User class to be 100% sure, but more then likely, the User class is not in the same package (or a subpackage) of your main class. This means that component scanning will not pick it up.
You can force spring to look at other packages like this: