I'm having a well working library and I would like to utilize the library in one of my sample Spring boot console application.
I built the library using the command mvn clean install
and the newly generated .jar file I imported in my sample Spring boot console application.
I created a bean in my new sample application and tried to create an object of UserManagementService
, which is in the external .jar and the said jar internally has two properties
External Jar's - Service file
public class UserManagementService {
@Autowired
UserService userService;
@Autowired
ManagementService managementService;
public String getUserFirstName(String userName) {
return userService.getUserFirstName(userName);
}
.. Rest of the implementation
}
These two autowired is not working and it has the value null moreover it throws an exception org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class...
My Sample Application:
public class ApplicationBean {
private UserManagementService userService = new UserManagementService();
public void run() {
if(userService == null) {
System.out.println("Oops");
}
String userFirstName = userService.getUserFirstName("Emma");
... Rest of the implementation
}
}
Kindly assist me how to fix this.
You need to declare your user management service as a bean in order to be able to inject it.
First Approach Annotate the UserManagementService
class with @Service
if you have control over the library, UserService
and ManagementService
needs to be annotated with @Service
too so they can be injected into UserManagementService
. You may need to use @ComponentScan(basePackages = { "libray.package" })
in your spring app (over main class) to make it scan your library and load the services.
Second Approach You make your library framework independent and make UserManagementService
a simple POJO where you pass UserService
and ManagementService
as constructor arguments, then declare those beans in your spring app
public class ApplicationBean {
@Bean
public UserService userServiceProvider(){
return new UserService();
}
@Bean
public ManagementService managementServiceProvider(){
return new ManagementService();
}
@Bean
public UserManagementService userManagementServiceProvider(UserService userService, ManagementService managementService){
return new UserManagementService(userService, managementService);
}
}
These beans declaration go to application main class or to a class annotated with @Configuration
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.