Search code examples
springspring-annotations

Is there an easy way to figure out why global spring beans are being constructed and initialized multiple times?


My application takes a long time to start.

There are some stateful factory beans that are supposed to be global singleton beans that are being initialized multiple (6) times. These are rather large beans that take some time to initialize.

The class Config1.java contains this annotation:

@EnableTransactionManagement
@ComponentScan({ 
    "com.myapp.svc.*", 
    "com.myapp.tools.*", 
    "com.myapp.core", 
    "com.myapp.notification.*",
    "com.myapp.jdbc.*", 
    "com.myapp.spring", 
    "com.myapp.exceptions.svc", 
    "com.myapp.exceptions.svc.dao" })

The class AppInitializer contains this onStartup method:

public void onStartup(ServletContext container) throws ServletException {
            AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(Config1.class);
        rootContext.register(Config2.class);
        rootContext.register(Config3.class);
        rootContext.register(Config4.class);
        rootContext.register(Config5.class);
        rootContext.register(Config6.class);
        rootContext.refresh();
}

A sample of a class that is being initialized multiple times is this:

@Component("someStatefulFactory")
@DependsOn({ "configPropertiesService", "sqlDialectFactory" })
@Scope(value = "singleton", proxyMode = ScopedProxyMode.DEFAULT)
@Order(2)
public class SomeStatefulFactoryImpl {

    public void somefactoryMethod() {
    }

}

It almost appears that the @ComponentScan annotation is evaluated during the refresh() once for every call to register().

Do you have any suggestions or ideas how I can track and fix this?

Thank you in advance.


Solution

  • The root of the problem is that @ComponentScan was overused and under filtered, plus the beans were being instantiated in an @Configuration factory class. The solution is to choose one model of instantiation and get the bean generation under control.