1

I have read at multiple stackoverflow questions that applicationContext.getbean is a bad idea.

Why is Spring's ApplicationContext.getBean considered bad?

I want to know if there is a better way of scanning beans of a given type in spring.

My use case is to get beans of a given type during spring start up and invoke some methods on those beans.

From what I know there are only two ways of doing this.

  1. Either autowire application context into a spring bean and use appContext.getBeansOfType.
  2. Hook in a postprocessor and filter our beans of given type by

    if(bean instance of type)

I feel hooking in a postprocessor just to process beans of one type is not a good idea. Because that will intercept all the bean initializations.

Can anyone suggest a better approach to solving my use case? (getBeans of a given type)

Community
  • 1
  • 1
yaswanth
  • 2,349
  • 1
  • 23
  • 33

1 Answers1

2

Spring has special handling of List autowired parameters. If you specify a bean e.g. like this:

@Component
class MyBean {
  @Autowired
  MyBean(List<MyType> listOfMytype) {

  }
}

Then spring will not search your applicationContext for a bean of type List<MyType>, but instead it will search for all beans that implement MyType and will inject those as a list (which may suck if you actually want to get a list injected). Thus you get all beans of a given type.

Community
  • 1
  • 1
yankee
  • 38,872
  • 15
  • 103
  • 162
  • thanks for the answer. I have one more question. What is wrong in using applicationContext.getBeansOfType in this case? We are not coupling the code to a concrete class. We are coupling it to an abstract class (or possibly an interface) which we are anyway doing by autowiring a list of beans of that type. – yaswanth Jan 25 '17 at 13:08
  • @yaswanth: I think that fits much better into the question that you linked. To my surprise none of the existing answers in this question have a direct example where you can see the effects. So I added one: http://stackoverflow.com/a/41853545/327301 – yankee Jan 25 '17 at 14:01