Using META-INF/spring.factories
and @AutoConfiguration
for automatic spring-boot applications configuration
Let's assume we would like to provide automatically HelloService
bean from my.annotation:library
module (producer)
and use it inside my.annotation:application
main application module consumer...
Import functionality by using dependency and @Import
annotation on consumer side
Implement service in HelloService.java file
@Service
public class HelloService {
public String greeting(String name) {
var person = Optional.ofNullable(name)
.filter(Predicate.not(String::isBlank))
.orElse("Buddy");
return String.format("Hello, annotated %s!", person);
}
}
Do not forget add @SpringBootApplication
annotation in based package of producing library in HelloLibraryAutoConfiguration.java
@SpringBootApplication
public class HelloLibraryAutoConfiguration { }
Add dependency in consumer pom.xml
<dependencies>
<dependency>
<groupId>my.annotation</groupId>
<artifactId>library</artifactId>
</dependency>
</dependencies>
Import auto-configuration in main application class, file HelloApplication.java
@SpringBootApplication
@Import(HelloLibraryAutoConfiguration.class)
public class HelloApplication { /* ... */ }
Inject service from auto-configuration in HelloHandler.java file
@Service
public class HelloHandler {
private final HelloService helloService;
public HelloHandler(HelloService helloService) {
this.helloService = helloService;
}
// ...
}
import functionality automatically just by adding dependency on consumer side
Now let's assume we would like to provide automatically same HelloService
bean but this time from
my.spring.factories:library
module (producer) and use it inside my.spring.factories:application
main application module consumer...
Implement service in HelloService.java
public class HelloService {
public String greeting(String name) {
var person = Optional.ofNullable(name)
.filter(Predicate.not(String::isBlank))
.orElse("Buddy");
return String.format("Hello, spring.factories %s!", person);
}
}
Do not forget add @Bean
in library auto-configuration HelloLibraryAutoConfiguration.java file
@Configuration
public class HelloLibraryAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public HelloService helloService() {
return new HelloService();
}
}
configure new auto-configuration in src/main/resources/META-INF/spring.factories file
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
my.spring.factories.HelloLibraryAutoConfiguration
Add dependency in consumer pom.xml
<dependencies>
<dependency>
<groupId>my.spring.factories</groupId>
<artifactId>library</artifactId>
</dependency>
</dependencies>
Inject service from producer auto-configuration HelloHandler.java
@Service
public class HelloHandler {
private final HelloService helloService;
public HelloHandler(HelloService helloService) {
this.helloService = helloService;
}
// ...
}