简体   繁体   中英

AnnotationSessionFactoryBean and singleton scoped bean (Spring framework)

I define a bean of type AnnotationSessionFactoryBean for using in a web-app.

If I do not explicitly define it as NOT singleton, it must be singleton.

Now, it is bound to the current thread.

It means it cannot be a singleton.

ps Session produced by Factory is not a singleton, SessionFactory on the other hand is always a singleton. Now everything is clear!

The AnnotationSessionFactoryBean (its superclass) defines the isSingleton() method which returns true. So the SessionFactory returned by this factory bean is singleton.

On the other hand, the Session that the SessionFactory produces may be thread-bound.

So you have:

BeanFactory creates SessionFactory creates Session

The superclass of AnnotationSessionFactoryBean called LocalSessionFactoryBean has some ThreadLocal<?> static fields:

private static final ThreadLocal<DataSource> configTimeDataSourceHolder =
        new ThreadLocal<DataSource>();

private static final ThreadLocal<TransactionManager> configTimeTransactionManagerHolder =
        new ThreadLocal<TransactionManager>();

private static final ThreadLocal<Object> configTimeRegionFactoryHolder =
        new ThreadLocal<Object>();

private static final ThreadLocal<CacheProvider> configTimeCacheProviderHolder =
        new ThreadLocal<CacheProvider>();

private static final ThreadLocal<LobHandler> configTimeLobHandlerHolder =
        new ThreadLocal<LobHandler>();

So even a single instance of this bean might interact differently in different threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM