Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q about AbstractApplicationContext.getBeansOfType() and getBean()

Tags:

java

spring

We have the following legacy 2.0.7 Spring code:

final Map<String, MyClass> secondaryFactories
     = (Map<String, MyClass>) context.getBeansOfType(MyClass.class, 
                                                     false, true);

return (MyClass) context.getBean("myClass");

where context is an instance of

org.springframework.context.support.AbstractApplicationContext

Note that we ignore the return value of getBeansOfType(). This works just fine, but the problem is that the call to getBeansOfType() is time-consuming. However, even though we ignore the return value of this call, if we try to eliminate this call, then the instance of MyClass returned by getBean() is not fully initialized. (So, apparently, the call to getBeansOfType() is having some sort of side-effects that we need.)

We suspect that the call to getBeansOfType() is overkill and we could do something more lightweight so that the instance of MyClass obtained by the call to getBean() would be fully initialized (but it's not null and no exception is thrown).

So, is there a more efficient way of doing this?

like image 547
Paul Reiners Avatar asked Jun 05 '09 19:06

Paul Reiners


1 Answers

First of all I suggest turning on logging and seeing what goes on. Spring is usually quite helpful.

Second of all, one difference between context.getBeansOfType and context.getBean is that getBeansOfType does not query the parent context. If you have one, you might hit a difference here.

Third of all, I assume the 'driver' bean is lazily initialised. Do you have any sort of multi-threaded code running while the context is initialized? There have been reports of fixes late in the 2.5 cycle related to that. getBeansOfType might be just generating a delay or hitting a memory barrier so that the issue with getBean returning an uninitialised bean is hidden.

Fourth of all, you might want to - just for argument's sake - try running the application with Spring 2.5.6. If it works, you know the guilty party.

like image 172
Robert Munteanu Avatar answered Oct 22 '22 17:10

Robert Munteanu