I have created by own library(com.custom.mylib) which returns a string like below.
@Component
public class MyLibrary{
@Value("${str.message}")
private String message; //This val should come from app which is going to use this lib
public String readMessage() {
return message;
}
I have create a project which is going to use above library. I have included the lib as pom dependency .But when I try to call library method from my app. I get the error below. How to resolve it?
@Autowired
private MyLibrary myLibrary;
Consider defining a bean of type 'com.custom.mylog.MyLibrary' in your configuration.
I also have below in application.properties file so that library can pick the value up
str.message=Hello world
CodePudding user response:
I got the solution it seems.I need to create META-INF file and do org.springframework.boot.autoconfigure.EnableAutoConfiguration=<fully_qualified_name_of_configuration_file>
as given here Spring Boot: autowire beans from library project
CodePudding user response:
As it has to be used as a external library, you can instantiate it throught a @Configuration
file:
@Configuration
public class AppConfiguration {
@Bean
public MyLibrary createMyLibraryInstance() {
return new MyLibrary();
}
}
The rule I used is the follow (this is not an universal rule):
- In your domain classes (Controller, Service) : use
@Autowired
in your constructor. It is the recommanded way to inject your dependencies. - You want to use external classes : implements a Java Configuration with
@Configuration
annotation, to instanciate your external classes as beans. - You want to create custom utilities classes : decorate it with
@Component
. - When you have more than on implementation, use
@Qualifier
and define your beans in a@Configuration
class.