简体   繁体   中英

Make all Spring beans of a certain type request scoped

I have a class and I want all objects of that type to be request scoped. In my Spring XML, I'm creating a list of such objects. It's very tedious and error-prone to have to set the scope and proxy mode for each one of these beans, so is there a way to make all beans of this type request scoped automatically?

I tried annotating the class with @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) but it didn't seem to work. Maybe the annotation is ignored when the bean is created via XML?

Here's what I have so far in XML:

<util:list>
    <bean class="com.test.MyClass" scope="request">
        <aop:scoped-proxy/>
        <constructor-arg>
            <bean value="Hello"/>
        </constructor-arg>
    </bean>
    <bean class="com.test.MyClass" scope="request">
        <aop:scoped-proxy/>
        <constructor-arg>
            <bean value="Friend"/>
        </constructor-arg>
    </bean>
</util:list>

And my class:

public class MyClass {
    private String value;

    public MyClass() { /* Default constructor */ }

    public MyClass(String value) {
        this.value = value;
}

Basically I am wondering if there is a way I can avoid having to add scope="request" and <aop:scoped-proxy/> to every bean of type MyClass and have them be request scoped automatically.

You might try to annotate the class with @Component in addition with @Scope. You will need to add a configuration class with @Configuration and @ComponentScan within the package to allow the scanning of the component.

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