Ravi
Ravi

Reputation: 195

Component scan using custom annotation

I am consuming a spring boot project as jar inside another spring boot application using the maven dependency. I want to do the component scan of jar only if I enable a custom annotation from microservice.

@SpringBootApplication
//@ComponentScan({"com.jwt.security.*"})  To be removed by custom annotation
@MyCustomAnnotation  //If I provide this annotation then the security configuration of the jar should be enabled.
public class MicroserviceApplication1 {

    public static void main(String[] args) throws Exception {

        SpringApplication.run(MicroserviceApplication1.class, args);

    }

}

Please suggest some ideas.

Upvotes: 6

Views: 3037

Answers (2)

Fabio Formosa
Fabio Formosa

Reputation: 1084

In your library:

@Configuration
@ComponentScan(basePackages = { "com.jwt.security" })
public class MyCustomLibConfig{

}


@Retention(RUNTIME)
@Target(TYPE)
@Import(MyCustomLibConfig.class)
public @interface MyCustomAnnotation{

 @AliasFor(annotation = Import.class, attribute = "value")
           Class<?>[] value() default { MyCustomLibConfig.class };
}

So, in your application you can use the annotation

@SpringBootApplication
@MyCustomAnnotation  //If I provide this annotation then the security configuration 
                       of the jar should be enabled.
public class MicroserviceApplication1 {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(MicroserviceApplication1.class, args);
    }

}

Upvotes: 4

StanislavL
StanislavL

Reputation: 57381

You can use @Conditional to define configurations (see an example describe here). Some code from the source

@Configuration
public class MyConfiguration {

  @Bean(name="emailerService")
  @Conditional(WindowsCondition.class)
  public EmailService windowsEmailerService(){
      return new WindowsEmailService();
  }

  @Bean(name="emailerService")
  @Conditional(LinuxCondition.class)
  public EmailService linuxEmailerService(){
    return new LinuxEmailService();
  }
}

and conditional

public class WindowsCondition implements Condition{

  @Override 
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    return context.getEnvironment().getProperty("os.name").contains("Windows");
  }
}

You can use profiles. Just add the @Profile to your config class with scan of desired package.

One more alternative is described here.

@AutoconfigureAfter(B.class)
@ConditionalOnBean(B.class)
public class A123AutoConfiguration { ...}

Upvotes: 0

Related Questions