Spring Boot: Custom auto-configuration JARs

Custom auto-configuration JAR: A shared JAR module containing Spring beans that can be automatically activated in one or more Spring Boot applications.

Auto-configuration JARs are extensively used by the official Spring Boot starter modules you are using in your every-day Spring Boot applications. But did you know that you easily can create such functionality yourself too?

Here’s how to do it. From your shared Java project, start by creating a Spring @Configuration:

[code language=”Java”] @Configuration @ConditionalOnWebApplication @ConditionalOnClass(EndpointHandlerMapping.class) public class DumpAutoConfiguration {

@Bean @Qualifier(“title”) public String dumpUiTitle() { return “UI Dump” ; }

} [/code]

Then tell Spring Boot that this is an auto-configuration JAR by adding a META-INF/spring.factories file to the classpath:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.moelholm.tools.actuatorui.dump.DumpAutoConfiguration

Done.

About the example

Did you notice the annotations @ConditionalOnWebApplication and @ConditionalOnClass? They are used to ensure that the configuration is only activated if the target Spring Boot application environment satisfies some expected circumstances.

The Spring Boot application that includes this JAR will now have a new bean in the ApplicationContext: dumpUiTitle. This bean can be injected like any other bean:

[code language=”Java”] @Autowired @Qualifier(“title”) private String title; [/code]

The example code above is inspired by the actuator-ui-dump JAR I developed a while ago. This JAR registers a new Spring MVC controller that renders a UI on top of the dump actuator endpoint. For details about the actuator-ui-dump: see my previous post.

It is very different from a typical JAR file. A typical JAR file is passive: it only contributes classes and resources that you then need to manually use from your application. The Spring Boot custom auto-configuration JAR files contributes services to the application. It could be Spring MVC HandlerInterceptors, Spring AOP aspects or whatever else you can do with a typical Spring application. And all your Spring Boot applications need to do is: add the JAR to the classpath.

The Spring Boot reference manual has more detailed information on the subject - see [1]. If you want to see the example code above in it’s actual context - then see the source code on GitHub [2].

References

[1] Spring Boot reference manual - on auto-configuration: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-understanding-auto-configured-beans

[2] Source code for the actuator-ui-dump module on GitHub: https://github.com/nickymoelholm/tools/tree/master/actuator-ui-dump