Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: get all Beans of certain interface AND type

In my Spring Boot application, suppose I have interface in Java:

public interface MyFilter<E extends SomeDataInterface>  

(a good example is Spring's public interface ApplicationListener< E extends ApplicationEvent > )

and I have couple of implementations like:

@Component public class DesignatedFilter1 implements MyFilter<SpecificDataInterface>{...}  @Component public class DesignatedFilter2 implements MyFilter<SpecificDataInterface>{...}  @Component public class DesignatedFilter3 implements MyFilter<AnotherSpecificDataInterface>{...} 

Then, in some object I am interested to utilize all filters that implement MyFilter< SpecificDataInterface > but NOT MyFilter< AnotherSpecificDataInterface >

What would be the syntax for this?

like image 239
onkami Avatar asked Oct 27 '16 13:10

onkami


People also ask

How do I get all beans in Spring boot?

In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.

How can we get list of all beans used in Spring application?

We can get a list of all beans within this container in two ways: Using a ListableBeanFactory interface. Using a Spring Boot Actuator.

Is @bean and @component same?

@Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a class's source code is editable. @Bean can always be used, but it's more verbose. @Component is compatible with Spring's auto-detection, but @Bean requires manual class instantiation.

What is @configuration and @bean in Spring?

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.


1 Answers

The following will inject every MyFilter instance that has a type that extends SpecificDataInterface as generic argument into the List.

@Autowired private List<MyFilter<? extends SpecificDataInterface>> list; 
like image 167
mh-dev Avatar answered Sep 22 '22 00:09

mh-dev