javaspring-bootspring-boot-starterspring-boot-configuration

How to check if an spring boot application has a certain annotation in autoconfiguration class


I am creating my own spring boot starter to centralise some common configurations in my projects. I would like to let on of my @Configuration classes be only matched, if my spring boot app is annotated in a certain way like so:

@SpringBootApplication
@EnableResourceServer
public class MyApplication {
...

When i use @ConditionalOnClass:

@Configuration
@ConditionalOnClass({EnableResourceServer.class})
class ResourceServerAutoConfiguration 

the auto configuration matched when the dependency is used even when the app is not a resource server (annotation is not present).

Is there a condition that only matches when the spring boot app has a certain annotation present?


Solution

  • I believe the simplest way would be to

    1. Add the @Import annotation to your @EnableResourceServer annotation class and pass in your configuration class
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Import(ResourceServerAutoConfiguration.class)
    public @interface EnableResourceServer {
    }
    
    1. Remove ResourceServerAutoConfiguration from the auto configuration block of the spring.factories file so it is no longer autoconfigured.

    This should result in the config only being loaded when the annotation is present ie.

    @SpringBootApplication
    @EnableResourceServer
    public class NotificationAdapterApplication {
    }