kayahr
kayahr

Reputation: 22070

Spring injection via javax.inject.Provider MUCH too slow

We use Spring dependency injection in a large web application. There are services which must work with request or session data and we implemented it with the javax.inject.Provider interface like this (We use constructor injection but in this example I inject the provider directly into a field so the example is shorter):

@Service
public class SomeService()
{
    @Autowired
    public Provider<Data> dataProvider;

    public void doSomething()
    {
        Data data = this.dataProvider().get()

        ...Do something with the request...
    }
}

In this example Data is some session-scoped data. The service itself is a singleton.

The problem now is that the dataProvider.get() call is WAY too slow. It needs several seconds to complete. I debugged the call and found out that the time is burned somewhere in the method DefaultListableBeanFactory.getBeanNamesForType. In this method a list of all bean definition names is fetched (Which contains more than 1000 names (We have lots of controllers, DAOs and services...) and iterated to find the bean to inject.

This is pretty much useless if it is that slow. I'm shocked that we have so many Spring beans already but isn't there a way to improve the lookup speed of javax.inject.provider stuff or a nice different way to solve this kind of injection? Maybe there is some way to define our own provider implementations which Spring could inject so it doesn't search for matching beans everytime the Provider.get() method is called?

Upvotes: 1

Views: 3480

Answers (2)

Ran Biron
Ran Biron

Reputation: 6365

7 years later, Provider<> injection is still slow. See Spring injection of Provider<String> is slow for possible workaround.

Upvotes: 0

Alex Barnes
Alex Barnes

Reputation: 7218

The performance of DefaultListableBeanFactory.getBeanNamesForType was raised as an issue and has been fixed in Spring 3.2.

The issue is here

You can try the 3.2 M1 to see if it improves the situation.

Upvotes: 2

Related Questions