springspring-bootdependency-injectionconcurrencyscope

Why is a Thread-Scoped Bean Injected Instead of a Default-Scoped Bean in Spring Boot?


I recently made a change to my Spring Boot project. I initially had a bean without a specific scope. Due to an implementation that uses threads and the occurrence of concurrency issues, I needed to create another bean identical to the previous one but with a thread scope using SimpleThreadScope. However, when I use the first bean in a service for batch processing, the second bean is mistakenly injected, even though the references indicate the first bean. To solve this problem, I cannot add qualifiers to the beans because the project is very large.

Below is the structure of my code.

app-config.xml

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="thread">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>


<bean id="reportService" class="it.myproject.service.report.ReportService">
    <property name="exporter" ref="exporter" />
    <property name="writer" ref="writer" />
</bean>


<bean id="reportServiceAsync" class="it.myproject.service.report.ReportService" scope="thread">
    <aop:scoped-proxy/>
    <property name="exporter" ref="exporter" />
    <property name="writer" ref="writer" />
</bean>



<bean id="myMagicBean" class="it.myproject.batch.MyMagicBean">
    <property name="reportService" ref="reportService" />
</bean>

I'm having trouble understanding why myMagicBean injects reportServiceAsync instead of reportService, as defined in my configuration.

How can I resolve this issue? Can anyone explain why this is happening?

Thank you very much in advance for your help.


Solution

  • Thanks to @M.Deinum's comment, I realized that the issue was in my ReportService, and that using thread scope was not appropriate. I resolved the problem by removing the shared attributes between the various methods.