user3908406
user3908406

Reputation: 1786

Spring filter beans based on annotation ignoring property values

Here is a simple example:

@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Type {
    public String name();
}


@Configuration
public class Configuration {
    @Bean
    @Type(name = "type1")
    public String getType1() {...}

    @Bean
    @Type(name = "type2")
    public String getType2() {...}

    ...
    
    @Bean
    @Type(name = "typeN")
    public String getTypeN() {...}
}


public class Test {

    @Autowired
    @Type // Here I'm asked to specify a name, but I want to get all the beans with @Type annotation regardless of the name property.
    private List<String> types;
}

As mentioned in the comment, I want to find all the beans with annotation @Type regardless of the name property. How can achieve it?

Upvotes: 1

Views: 199

Answers (1)

badger
badger

Reputation: 3246

A not good workaround to achieve it:

@Retention(RetentionPolicy.RUNTIME)
@Qualifier(value = "Type") // --> add this line
public @interface Type {
  public String name();
}

and autowire it like this:

@Component
public class Test {
  @Autowired
  @Qualifier(value = "Type")
  private List<String> types;

  public void printAll(){
    System.out.println(types);
  }
}

Upvotes: 2

Related Questions