使用自定义注释进行组件扫描

时间:2017-11-30 04:24:04

标签: java spring maven spring-boot annotations

我正在使用maven依赖项在另一个Spring启动应用程序中将jar启动项目作为jar使用。我只想在微服务中启用自定义注释时才进行jar的组件扫描。

@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);

    }

}

请提出一些建议。

2 个答案:

答案 0 :(得分:0)

您可以使用@Conditional来定义配置(请参阅描述here的示例)。来自源的一些代码

@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();
  }
}

和条件

public class WindowsCondition implements Condition{

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

您可以使用个人资料。只需将@Profile添加到配置类中,并扫描所需的包。

另一个替代方案是here

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

答案 1 :(得分:0)

在您的书架中:

@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 };
}

因此,在您的应用程序中,您可以使用注释

@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);
    }

}